python 如何基于paramiko写一个持续交互命令?
使用场景 我需要执行一系列sh命令,这些sh命令有上下依赖关系,比如切换到某个目录,然后再执行其他命令。
需要 可以实现命令的连续性。
import time
import paramiko
import re
class SSHConnection(object):
def __init__(self, host_dict):
self.host = host_dict['host']
self.port = host_dict['port']
self.username = host_dict['username']
self.pwd = host_dict['pwd']
def connect(self):
# 连接
transport = paramiko.Transport((self.host, self.port))
transport.connect(username=self.username, password=self.pwd) # 通道建立连接
self.__transport = transport
channel = transport.open_session()
channel.get_pty()
channel.invoke_shell()
self.__channel = channel # 建立持续交互
def close(self):
# 关闭
self.__transport.close()
self.__channel.close()
def run_shell(self,command):
# 执行shell命令,持续交互
channel = self.__channel # 获取通道
channel.send(f'{command}\n') # 执行命令
result = '' # 存放结果
while True: # 有可能有多行数据 用循环
time.sleep(0.5)
res = channel.recv(65535).decode('utf8')
result += res
if res.endswith('# ') or res.endswith('$ '): # 终止条件
break
result = re.sub('\x1b.*?m', '', result) # 移除\xblah[0m这些
return result.strip('\n') # 移除
def upload(self, local_path, target_path):
# 连接,上传
sftp = paramiko.SFTPClient.from_transport(self.__transport)
# 将location.py 上传至服务器 /home/test.py
sftp.put(local_path, target_path, confirm=True)
# 增加权限
sftp.chmod(target_path, 0o755) # 注意这里的权限是八进制的,八进制需要使用0o作为前缀
def download(self, target_path, local_path):
# 连接,下载
sftp = paramiko.SFTPClient.from_transport(self.__transport)
# 将/home/test.py 下载至本地 location.py
sftp.get(target_path, local_path)
def __del__(self):
# 销毁
# self.close()
'''下面的代码是为了解决执行中遇到的'NoneType' object has no attribute 'time' 报错'''
try:
self.close()
except Exception as e:
if str(e) != "'NoneType' object has no attribute 'time'":
raise
if __name__ == '__main__':
host_dict={
"host":"192.168.53.77",
"port": 22,
"username": "liqi",
"pwd": "123456",
}
obj = SSHConnection(host_dict=host_dict) # 实例化
obj.connect() # 建立一个终端连接
print(obj.run_shell('pwd'))
obj.run_shell('cd liqi')
print(obj.run_shell('pwd'))
参考资料
https://www.cnblogs.com/xiao-apple36/p/9144092.html