paramiko SSH 交互

原文出处 http://www.cnblogs.com/gannan/archive/2012/02/06/2339883.html

参考:https://github.com/paramiko/paramiko, 

            http://www.moojuice.net/posts/ython-pycrypto-2-4-1-32-and-64-bit-windows-32x64-amdintel-installers


paramiko ssh 命令

#!/usr/bin/env python

import paramiko

def main():
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect('10.239.254.175', 22, 'media', 'intel123')
    stdin, stdout, stderr = client.exec_command('/sbin/ifconfig')
    #print 'stderr', stderr
    #print 'stdout', type(stdout)
    for line in stdout:
        print '...' + line.strip('\n')
    client.close()
    print 'close'

if __name__ == '__main__':
    main()

上传文件

#!/usr/bin/env python

import paramiko

def main():
    host = ('10.239.254.175', 22)
    client = paramiko.Transport(host)
    client.connect(username='media', password='intel123')
    sftp = paramiko.SFTPClient.from_transport(client)
    remotePath = '/var/Clips/Public/Zhubinqiang/Script/para2.py'
    localPath = './para2.py'
    s = sftp.put(localPath, remotePath)
    #print s
    client.close()
    print 'close'

if __name__ == '__main__':
    main()

windows上传文件夹到Linux

def _get_sftp(hostname, port, username, password):
    t = paramiko.Transport((hostname, port))
    t.connect(username=username, password=password)
    sftp = paramiko.SFTPClient.from_transport(t)
    return sftp

def _get_client(hostname, port, username, password):
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(hostname=hostname, port=port, username=username, password=password)
    return client

def scpDir(hostname, port, username, password, localDir, remoteDir):
    sftp = _get_sftp(hostname, port, username, password)
    client = _get_client(hostname, port, username, password)
    
    for parent, dirnames, filenames in os.walk(localDir):
        for dirname in dirnames:
            rdir = os.path.join(parent, dirname).replace("\\", '/')
            command = 'mkdir %s/%s' %(remoteDir, rdir)
            print command
            client.exec_command(command)
        
        for filename in filenames:
            f = os.path.join(parent, filename)
            remotefile = remoteDir + '/' + f.replace('\\', '/')
            print 'scp %s %s' %(f, remotefile)
            sftp.put(f, remotefile)
    sftp.close()
    client.close()


def test_scpDir():
    localDir = '.'
    remoteDir = '/home/bzhux/WorkSpace/Script/test/t'
    
    hostname = '10.239.254.183'
    port = 22
    username = 'bzhux' 
    password = '123456'
    scpDir(hostname, port, username, password, localDir, remoteDir)





你可能感兴趣的:(Linux,Python)