Paramiko基本用法

先安装Python。支持版本Python 2.6,2.7,3.3+。另外Paramiko还依赖Cryptography library。

然后安装paramiko:

pip install paramiko

主要功能:

1 执行命令

import paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
r=ssh.connect("10.99.206.27",22,"wcadmin", "<password>")
stdin, stdout, stderr = ssh.exec_command("export")
lines=stdout.readlines()
print type(lines)
for line in lines:
    print line
ssh.close()
print '-'*20

2 下载文件

t=paramiko.Transport(('10.99.206.27',22))
t.connect(username='wcadmin',password='<password>')
sftp=paramiko.SFTPClient.from_transport(t)
remote_path='/home/wcadmin/test.txt'
local_path="D:\\temp\\tmp\\jumpserver_page\\test.txt"
sftp.get(remote_path,local_path)
t.close()

3 上传文件

t=paramiko.Transport(('10.99.206.27',22))
t.connect(username='wcadmin',password='<password>')
sftp=paramiko.SFTPClient.from_transport(t)
remote_path='/home/wcadmin/test.txt'
local_path="D:\\temp\\tmp\\jumpserver_page\\test.txt"
sftp.put(local_path,remote_path)
t.close()

上传下载默认将会覆盖同名文件。

4 命令行方式与远程服务器交互(基于windows平台)


#-*-coding:UTF-8-*-

import sys
import paramiko
import threading

def read_chan(chan):
    while True:
        data=chan.recv(256)
        if not data:
            sys.stdout.write('\r\n*** EOF ***\r\n\r\n')
            sys.stdout.flush()
            break
        sys.stdout.write(data)
        sys.stdout.flush()
    pass

if __name__=='__main__':
    print 'interactive shell command'+'-'*20
    client=None
    chan=None
    try:
        client=paramiko.SSHClient()
        client.load_system_host_keys()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client.connect('10.99.206.27',22,'wcadmin','<password>')
        chan=client.invoke_shell()
        
        threading.Thread(target=read_chan,args=(chan,)).start()
        while True:
            d=sys.stdin.read(1)
            if not d:
                break
            chan.send(d)
        
    except paramiko.ssh_exception.AuthenticationException,e:
        print('Exception ---> '+str(e))
    except SSHException,sshe:
        print("SSHException ---> "+str(sshe))
    except BaseException,be:
        print("Other Exception ---> "+str(be))
    finally:
        if chan:
            chan.close()
        if client:
            client.close()
        
    print 'end of test'+'*'*20

 

转载于:https://my.oschina.net/shawnplaying/blog/687697

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值