工作需要,經常會用xshell連接遠程linux機器,查看上面的一些文檔信息,然後不斷的切換目錄,cd.....cd......,心累!!
爲啥不用腳本去實現呢?去網上翻閱了一些資料,果然有解決方案,感謝分享成果的IT人,這裏分享下我的體會吧。
1、 安裝相關支撐庫:
安裝pycrypto:http://www.voidspace.org.uk/python/modules.shtml#pycrypto
安裝paramiko,https://pypi.python.org/pypi/paramiko/1.7.7.1
解壓到C盤下,cmd切換到對應目錄執行:python setup.py build ,接着執行 python setup.py install
2、 paramiko使用:
def get_search_text(self):
# SSH遠程連接
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host_ip, host_port, username, password)
# 待執行的命令
swithch_path = "cd docker/conf/"
search_contents = "grep 'game'config.xml"
# 注意:依次執行多條命令時,命令之間用分號隔開
command = swithch_path+";"+search_contents
# 執行命令
stdin, stdout, stderr = ssh.exec_command(command)
err = stderr.readlines()
out = stdout.readlines()
if len(err) != 0:
print "==execute command[",command, "] failed: ", err
else:
print "==execute command[",command, "] success: ", out
ssh.close()
return out
3、 定義好了這個方法,直接用ROBOT去調用就好了,以後直接運行robot的case,就可以獲取到想要的東東了!!