CentOS下安装使用Paramiko

Paramiko模块是Python使用ssh协议登陆远程机器的必备模块。

安装Python开发版

yum install python-devel

安装Paramiko

pip install Paramiko

看一下是否安装成功

python -c "import paramiko"

使用示例

Example 1 : 执行远程命令,并打印执行结果

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import paramiko

ip = "123.456.789.10"
port = 22
username = "root"
passwd = "123456789"
command = "ifconfig"

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip, port, username, passwd)
stdin, stdout, stderr = ssh.exec_command(command)
print stdout.readlines()
ssh.close()

Example 2 : 上传指定文件到远程

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import paramiko

ip = "123.456.789.10"
port = 22
username = "root"
passwd = "123456789"

trans = paramiko.Transport((ip, port))
trans.connect(username = username, password = passwd)

sftp = paramiko.SFTPClient.from_transport(trans)
localfile = "/root/test.cfg"
remotefile = "/root/testcopy.cfg"
sftp.put(localfile, remotefile)
trans.close()