ftp使用内置模块from ftplib import FTP
sftp使用import paramiko
[url=http://www.lag.net/paramiko/]paramiko SSH2 protocol for python [/url] 协议:LGPL V2.1
上述包依赖:
[url=https://www.dlitz.net/software/pycrypto/]Python Cryptography Toolkit (pycrypto)[/url]
pycrypto安装时需要Visual2003的编译环境
pycrypto安装包,已编译版本:http://www.voidspace.org.uk/python/modules.shtml#pycrypto(或者直接把Crypto解码到Python25\Lib\site-packages文件夹)
详细使用说明参考:安装目录site-packages下的paramiko-1.7.7.1\demos
通过ssh2执行shell脚本
通过ssh2执行交互式shell脚本
# ftp settings
ftp_server = "192.168.0.1"
ftp_port = "21"
ftp_user = "user"
ftp_password = "pwd"
def ftp_stor_files(file_zip):
cmd_stor = "STOR %s" %(os.path.split(file_zip)[1])
print(cmd_stor)
ftp = FTP(ftp_server, ftp_user, ftp_password)
ftp.getwelcome()
ftp.storbinary(cmd_stor, open(file_zip, "rb"), 1024)
ftp.close()
#ftp.quit()
sftp使用import paramiko
[url=http://www.lag.net/paramiko/]paramiko SSH2 protocol for python [/url] 协议:LGPL V2.1
上述包依赖:
[url=https://www.dlitz.net/software/pycrypto/]Python Cryptography Toolkit (pycrypto)[/url]
pycrypto安装时需要Visual2003的编译环境
pycrypto安装包,已编译版本:http://www.voidspace.org.uk/python/modules.shtml#pycrypto(或者直接把Crypto解码到Python25\Lib\site-packages文件夹)
详细使用说明参考:安装目录site-packages下的paramiko-1.7.7.1\demos
# ftp settings
ftp_server = "192.168.0.1"
ftp_port = 22
ftp_user = "user"
ftp_password = "pwd"
def sftp_stor_files(file_zip, destFile):
t = paramiko.Transport((ftp_server, ftp_port))
t.connect(username=ftp_user, password=ftp_password, hostkey=None)
sftp = paramiko.SFTPClient.from_transport(t)
# dirlist on remote host
dirlist = sftp.listdir('.')
print "Dirlist:", dirlist
sftp.put(file_zip, destFile)
t.close()
通过ssh2执行shell脚本
def ssh2_exec_command(command):
print "ssh2 execute command: %s" %(command)
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ftp_server, username=ftp_user, password=ftp_password)
stdin, stdout, stderr = ssh.exec_command(command)
stdin.close()
for line in stdout.read().splitlines():
print line
for line in stderr.read().splitlines():
print "command error ---%s" %(line)
通过ssh2执行交互式shell脚本
def ssh2_exec_interactive_command():
print "ssh2 execute interactive command"
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ftp_server, username=ftp_user, password=ftp_password)
while True:
cmd = raw_input("Please Input Command to run in server %s : " %(ftp_server))
if cmd == "":
break
channel = ssh.get_transport().open_session()
print "running '%s'" % cmd
channel.exec_command(cmd)
print "exit status: %s" % channel.recv_exit_status()
print "exit status: %s" % channel.recv(10000)
ssh.close()