python登录服务器并执行命令

本文主要介绍在Windows上利用python登录远程服务器并执行命令的操作。
遇到的问题部分主要讲在运行python程序时遇到的问题及解决办法。
此外本文还介绍利用paramiko实现ssh的交互式连接,这样执行效果就像我们平时直接使用ssh登录一样。

python登录服务器并执行命令

利用paramiko模块,简单实现如下,在执行的时候可能会遇到缺少各种依赖的情况,解决方法参考第二部分“遇到的问题”

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#-*- coding: utf-8 -*-
#!/usr/bin/python
import paramiko

def ssh2(ip,username,passwd,cmd):
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,22,username,passwd,timeout=5)
for m in cmd:
stdin, stdout, stderr = ssh.exec_command(m)
# stdin.write("Y") #简单交互,输入 ‘Y’
out = stdout.readlines()
#屏幕输出
for o in out:
print o,
print '%s\tOK\n'%(ip)
ssh.close()
except :
print '%s\tError\n'%(ip)


if __name__=='__main__':
cmd = ['cal','echo hello!']#你要执行的命令列表
username = "" #用户名
passwd = "" #密码

ip = "192.168.0.1"
ssh2(ip,username,passwd,cmd)

遇到的问题

ImportError: No module named paramiko

解决方法:

Python中使用SSH需要用到OpenSSH,而OpenSSH依赖于paramiko模块,而paramiko模块又依赖于pycrypto模块,因此要在Python中使用SSH,需要先安装pycrypto工具,然后再安装paramiko模块才能使用。

首先要确保python安装好,且环境变量设置好。

参考文章:Windows下解决python - ImportError: No module named paramiko

ImportError: No module named Crypto

安装pycrypto:
到下面这个网站下载编译好的pycrypto
http://www.voidspace.org.uk/python/modules.shtml#pycrypto

安装完成后import Crypto成功则表示安装成功
参考文章:python安装Pycrypto(win10 64 python27)

importerror no module named cryptography.hazmat.backends

pip install cryptography(记得要退出python之后执行)

Command “python setup.py egg_info” failed with error code 1

安装第三方包的时候报错“Command “python setup.py egg_info” failed with error code 1”

解决方法:

更新pip

pip install –upgrade pip

再安装需要安装的第三方扩展包

importerror no module named bcrypt

pip install py-bcrypt

如果使用pip无法直接安装,另外一个办法就是直接下载源码安装
https://pypi.org/project/bcrypt/3.1.0/#files下载源码,然后
python setup.py build
python setup.py install

error: Microsoft Visual C++ 9.0 is required (Unable to find vcvarsall.bat)

请参考:Windows下安装Python扩展模块提示“Unable to find vcvarsall.bat”的问题

importerror no module named nacl.signing

pip install pynacl

利用paramiko实现ssh的交互式连接

以下是通过paramiko模块直接用ssh协议登陆到远程服务器的操作代码,这里先定义一个interactive模块,其文件名就叫interactive.py,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import socket
import sys
# windows does not have termios...
try:
import termios
import tty
has_termios = True
except ImportError:
has_termios = False
def interactive_shell(chan):
if has_termios:
posix_shell(chan)
else:
windows_shell(chan)
def posix_shell(chan):
import select
oldtty = termios.tcgetattr(sys.stdin)
try:
tty.setraw(sys.stdin.fileno())
tty.setcbreak(sys.stdin.fileno())
chan.settimeout(0.0)
while True:
r, w, e = select.select([chan, sys.stdin], [], [])
if chan in r:
try:
x = chan.recv(1024)
if len(x) == 0:
print 'rn*** EOFrn',
break
sys.stdout.write(x)
sys.stdout.flush()
except socket.timeout:
pass
if sys.stdin in r:
x = sys.stdin.read(1)
if len(x) == 0:
break
chan.send(x)
finally:
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
# thanks to Mike Looijmans for this code
def windows_shell(chan):
import threading
sys.stdout.write("Line-buffered terminal emulation. Press F6 or ^Z to send EOF.rnrn")
def writeall(sock):
while True:
data = sock.recv(256)
if not data:
sys.stdout.write('rn*** EOF ***rnrn')
sys.stdout.flush()
break
sys.stdout.write(data)
sys.stdout.flush()
writer = threading.Thread(target=writeall, args=(chan,))
writer.start()
try:
while True:
d = sys.stdin.read(1)
if not d:
break
chan.send(d)
except EOFError:
# user hit ^Z or F6
pass

再另外写一个ssh_inter.py的交互主程序,内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import paramiko
import interactive

#记录日志
paramiko.util.log_to_file('/tmp/test')
#建立ssh连接
ssh=paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('192.168.0.102',port=22,username='root',password='xxxxxx',compress=True)
#建立交互式shell连接
channel=ssh.invoke_shell()
#建立交互式管道
interactive.interactive_shell(channel)
#关闭连接
channel.close()
ssh.close()

运行上述代码会报“SyntaxError: Non-ASCII character ‘\xbc’ in file ssh_inter.py on line 4, but…”的错误
解决办法:
在第一行加入:
1
2
#-*- coding: utf-8 -*-
#!/usr/bin/python

之后执行python ssh_inter.py, 执行效果就像我们平时直接使用ssh登录一样。

参考资料

Windows下解决python - ImportError: No module named paramiko
python安装Pycrypto(win10 64 python27)
Windows下安装Python扩展模块提示“Unable to find vcvarsall.bat”的问题
ssh批量登录并执行命令(python实现)
python模块paramiko与ssh

如果你觉得本文对你有帮助,欢迎打赏