程序设计语言

python操作ssh(zz)

2010年8月28日 阅读(391)

以前操作ssh都是调用的外部命令,虽然简单,但是布署太麻烦。
比较了几个python操作ssh的库,paramiko这个库比较符合我的要求,小巧,功能专门针对ssh协议一族(ssh2, sftp等),
下载地址 http://www.lag.net/paramiko/
这个库依赖于 pycrypto 密码库
pycrypto 下载地址 http://www.dlitz.net/software/pycrypto/ 只有源码下载,python2.5用vc7.1编译,python2.6用vc9编译,支持x64位平台。
两个简单例子
#一个获取 ssh key文件并保存的函数
#host  ssh服务器ip或域名
#username 用户名
#passwd 密码
#savefilename 要保存的key文件路径
def getkeypub(host, username, passwd, savefilename):
    ssh_con = paramiko.SSHClient()
    ssh_con.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
        ssh_con.connect(hostname = host, username = username, 
                password = passwd)
    except paramiko.AuthenticationException:
        print ‘auth failed’
        return 1
    except socket.error:
        print ‘unable reach server’
        return 2
    ssh_con.save_host_keys(savefilename)
    ssh_con.close()
    return 0
#利用sftp获取文件
#host  ssh服务器ip或域名
#username 用户名
#passwd 密码
#keyfile key文件路径
#remotefile 要获取的ssh服务器上的文件路径
#localfile 保存到本地的路径
def sftpgetfile(host, username, passwd, keyfile, remotefile, localfile):
    ssh_con = paramiko.SSHClient()
    ssh_con.load_host_keys(keyfile)
    print ‘point1’
    try:
        ssh_con.connect(hostname = host, username = username, 
                password = passwd)
        print ‘point2’
    except paramiko.AuthenticationException:
        print ‘auth failed’
        return 1
    except socket.error:
        print ‘unable reach server’
        return 2
    sftp = ssh_con.open_sftp()
    sftp.get(remotefile, localfile)
    ssh_con.close()
    return 0

You Might Also Like