您的位置:首页 > 编程语言 > Python开发

python模块学习之paramiko远程执行命令,文件上传、下载

2018-03-07 21:55 1131 查看
原文链接:http://www.cnblogs.com/Detector/p/8176029.html  

paramiko简介

paramiko是用python语言写的一个模块,遵循SSH2协议,支持以加密和认证的方式,进行远程服务器的连接。

由于使用的是python这样的能够跨平台运行的语言,所以所有python支持的平台,如Linux, Solaris, BSD, MacOS X, Windows等都可以支持

远程执行命令

def ssh_connect(host, username, passwd, *commands):
"""远程连接执行命令"""
import paramiko
try:
# flag = True
ssh = paramiko.SSHClient()  # 建立一个ssh client对象
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())  # 使用自动保存服务器的主机名和密钥信息的策略
ssh.load_system_host_keys()  # 每次连线时都会检查host key 与纪录的 host key 是否相同
ssh.connect(hostname=host,
username=username,
password=passwd,
timeout=300)

result = {}
for command in commands:
stdin, stdout, stderr = ssh.exec_command(command)
result[command] = stdout.read(), stderr.read()   # 获取标准输出和标准错误输出的值
err_list = stderr.readlines()
if err_list:
print("ERROR: ",err_list[0])
exit(1)
break
ssh.close()
return result
except Exception as e:
print( 'ssh %s@%s: %s' % (username, host, e))


从服务器下载文件

def ssh_get_file(host, username, passwd, remotepath, localpath):
import paramiko
try:
ssh = paramiko.Transport(host)  # 建立一个连接对象
ssh.connect(username=username,
password=passwd
)

sftp = paramiko.SFTPClient.from_transport(ssh)
sftp.get(remotepath, localpath)
sftp.close()
except Exception as e:
print('Get data from %s@%s:%s, %s' % (username, host, remotepath, e))

4000

上传文件到服务器

def ssh_upload_file(host, username, passwd, localpath, remotepath):
import paramiko
try:
ssh = paramiko.Transport(host)  # 建立一个连接对象
ssh.connect(username=username,
password=passwd
)

sftp = paramiko.SFTPClient.from_transport(ssh)
sftp.put(localpath, remotepath)
sftp.close()
except Exception as e:
print('Get data from %s@%s:%s, %s' % (username, host, localpath, e))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐