H5W3
当前位置:H5W3 > python > 正文

python连接linux代码

python连接linux-云海天教程

"""
请使用python连接你的虚拟机,完成以下操作(定义到类和函数中):
1. 在当前python项目目录下创建work目录,并在其中创建同名文本文档work.txt,在txt文件中写入
当前日期的月和日即可
2. 连接虚拟机,将刚才写好的work.txt上传到虚拟机/home/目录下,同时将本地的work.txt删除。
3. Linuxetc目录下的passwd,shadow,group三个文件使用tar命令进行打包,包名为work.txt的内容加上文件的首字母,例如:0725p.tar.gz0725s.tar.gz0725g.tar.gz,将压缩后的三个
文件下载到本地work目录
"""

import paramiko
import os
import datetime
import shutil
class Client(object):
def __init__(self, ip, port, user, password, workpath, linuxpath):
self.ip = ip
self.port = port
self.user = user
self.password = password
self.workpath = workpath
self.linuxpath = linuxpath
def client1(self):
# 连接服务器执行命令
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(self.ip, self.port, self.user, self.password)
return ssh
def client2(self):
# 连接服务器传输文件
s = paramiko.Transport(self.ip, self.port)
s.connect(username=self.user, password=self.password)
p = paramiko.SFTPClient.from_transport(s)
return p
def file(self):
try:
if os.path.exists(self.workpath):  # 判断一下目录下是否有该文件/目录,如果存在则删除
shutil.rmtree(self.workpath)
else:
os.mkdir(self.workpath)
os.chdir(self.workpath)
with open("work.txt", "w+") as w:
w.write(str(datetime.datetime.now())[5:7]+str(datetime.datetime.now())[8:10])
print("work.txt已建立并写入数据")
except Exception as e:
print(e)
def put_file(self):
try:
p = self.client2()  #调用client2方法
if os.path.exists(self.workpath):
# 判断目录是否为空
f = os.listdir(self.workpath)
if len(f) == 0:
print("目录为空")
else:
tf = "".join(f)
# 上传文件
p.put(os.path.join(self.workpath, tf),f"{self.linuxpath}{tf}")
#删除本地文件
os.remove(os.path.join(self.workpath, tf))
#  listdir:以列表形式输出
if len(os.listdir(self.workpath)) == 0:
print("本地work.txt文件已删除")
else:
print("本地work目录路径不存在")
except Exception as e:
print(e)
def get_tar(self):
try:
s = self.client1()
p = self.client2()
stdin, stdout, stderr =s.exec_command(f"cat {self.linuxpath}/work.txt")
time = stdout.read().decode("utf-8")
filelist = ["passwd", "shadow", "group"]
for i in filelist:
# 遍历filelist列表,执行linux命令
s.exec_command(f"tar -zcvf {self.linuxpath}{time}{i[0]}.tar.gz /etc/{i}")
stdin, stdout, stderr = s.exec_command(f"cd {self.linuxpath};ls")
allstr = stdout.read().decode("utf-8").replace("", ",")
tarstr = allstr[:38]
tarlist = tarstr.split(",")
s = paramiko.Transport(self.ip, self.port)
s.connect(username=self.user, password=self.password)
p = paramiko.SFTPClient.from_transport(s)
for i in tarlist:
if os.path.exists(self.workpath):
p.get(self.linuxpath+i, os.path.join(self.workpath, i))
print(f"{i}已下载")
else:
print("本地work目录不存在,无法下载压缩包到本地")
except Exception as e:
print(e)
c =Client(# 传入参数)
c.file()
c.put_file()
c.get_tar()

本文地址:H5W3 » python连接linux代码