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

windows下python SSH的使用——paramiko模块

2014-03-20 23:37 633 查看
paramiko模块实例。

paramiko模块安装参考另一篇博文:/article/8285752.html

#!/usr/bin/python
import paramiko

server_ip = '192.168.*.*'
server_user = 'your_user'
server_passwd = 'your_password'
server_port = 22

def ssh_connect():
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(server_ip, server_port,server_user, server_passwd)
return ssh

def ssh_disconnect(client):
client.close()

def exec_cmd(command):
'''
windows客户端远程执行linux服务器上命令
'''
stdin, stdout, stderr = ssh.exec_command(command)
err = stderr.readline()
out = stdout.readline()

if "" != err:
print "command: " + command + " exec failed!\nERROR :" + err
return true, err
else:
print "command: " + command + " exec success."

def win_to_linux(localpath, remotepath):
'''
windows向linux服务器上传文件.
localpath  为本地文件的绝对路径。如:D:\test.py
remotepath 为服务器端存放上传文件的绝对路径,而不是一个目录。如:/tmp/my_file.txt
'''
client = paramiko.Transport((server_ip, server_port))
client.connect(username = server_user, password = server_passwd)
sftp = paramiko.SFTPClient.from_transport(client)

sftp.put(localpath,remotepath)
client.close()

def linux_to_win(localpath, remotepath):
'''
从linux服务器下载文件到本地
localpath  为本地文件的绝对路径。如:D:\test.py
remotepath 为服务器端存放上传文件的绝对路径,而不是一个目录。如:/tmp/my_file.txt
'''
client = paramiko.Transport((server_ip, server_port))
client.connect(username = server_user, password = server_passwd)
sftp = paramiko.SFTPClient.from_transport(client)

sftp.get(remotepath, localpath)
client.close()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: