python sftp&ftp&ssh2

ftp使用内置模块from ftplib import FTP

# 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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值