上传文件
import paramiko
from paramiko.ssh_exception import NoValidConnectionsError,AuthenticationException
def sftp_upload_file(server_path, local_path):
try:
t = paramiko.Transport((ip, 22))
t.connect(username=user, password=pwd)
sftp = paramiko.SFTPClient.from_transport(t)
sftp.put(local_path, server_path)
t.close()
except AuthenticationException as e:
return '主机%s密码错误' %(ip)
except Exception as e:
return '未知错误: ',e
finally: #不论初步出错,都会执行的代码
t.close()
下载文件
from paramiko.ssh_exception import NoValidConnectionsError,AuthenticationException
import paramiko
def sftp_down_file(server_path, local_path):
try:
t = paramiko.Transport((ip, 22))
t.connect(username=user, password=pwd)
sftp = paramiko.SFTPClient.from_transport(t)
sftp.get(server_path, local_path)
except AuthenticationException as e:
return '主机%s密码错误' %(ip)
except Exception as e:
return '未知错误: ',e
finally: #不论初步出错,都会执行的代码
t.close()
远程连接
def ssh_conn(cmd):
ssh = paramiko.SSHClient()
# 允许连接不在known_hosts文件上的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
#ssh.connect(ip, 22, user, pwd)
try:
client.connect(
hostname='172.25.0.1',
username='root',
password='redhat'
)
# 执行命令
stdin, stdout, stderr = ssh.exec_command(cmd)
# 获取结果
#print(stdout.read().decode('utf-8'))
a = stdout.read()decode('utf-8')
for line in stdout:
res=(line.strip('\n').split())
print(res)
else:
print(stdout)
return a
except NoValidConnectionsError as e:
return '主机%s连接失败' %(hostname)
except AuthenticationException as e:
return '主机%s密码错误' %(hostname)
except Exception as e:
return '未知错误:',e