最近想要實(shí)現(xiàn)通過(guò)腳本循環(huán)再 Linux 下運(yùn)行 shell 命令,經(jīng)過(guò)探索發(fā)現(xiàn)使用 Python 語(yǔ)言有幾種解決方案,在此簡(jiǎn)單記錄。
方案一:腳本本地執(zhí)行命令
在 Python 中有兩個(gè)庫(kù)都可以實(shí)現(xiàn)運(yùn)行 shell 命令的效果:
import subprocess
import os
使用方法也很簡(jiǎn)單:
# subprocess 使用方法
subprocess.call("ls") # 執(zhí)行l(wèi)s命令
# os 使用方法
# 使用system模塊執(zhí)行l(wèi)inux命令時(shí),如果執(zhí)行的命令沒(méi)有返回值res的值是256
# 如果執(zhí)行的命令有返回值且成功執(zhí)行,返回值是0
res = os.system("ls")
# popen模塊執(zhí)行l(wèi)inux命令。返回值是類(lèi)文件對(duì)象,獲取結(jié)果要采用read()或者readlines()
val = os.popen('ls').read() # 執(zhí)行結(jié)果包含在val中
方案二:腳本遠(yuǎn)程執(zhí)行命令
在 Python 中有一個(gè)庫(kù)可以實(shí)現(xiàn) SSH 客戶(hù)端及 SFTP 的功能。
#!/usr/bin/python
import paramiko
使用方法大致如下:
# 連接方法
def ssh_connect( _host, _username, _password ):
try:
_ssh_fd = paramiko.SSHClient()
_ssh_fd.set_missing_host_key_policy( paramiko.AutoAddPolicy() )
_ssh_fd.connect( _host, username = _username, password = _password )
except Exception, e:
print( 'ssh %s@%s: %s' % (_username, _host, e) )
exit()
return _ssh_fd
# 運(yùn)行命令
def ssh_exec_cmd( _ssh_fd, _cmd ):
return _ssh_fd.exec_command( _cmd )
# 關(guān)閉SSH
def ssh_close( _ssh_fd ):
_ssh_fd.close()
方案三:使用 SecureCRT 腳本
該方法參見(jiàn)此前的博文:SecureCRT 下 Python 腳本編寫(xiě)
參考文獻(xiàn)
- Python 學(xué)習(xí)總結(jié) 06 paramiko 遠(yuǎn)程執(zhí)行命令:https://www.cnblogs.com/wangshuo1/p/6265360.html
- Python 模塊學(xué)習(xí) - Paramiko:https://www.cnblogs.com/xiao-apple36/p/9144092.html
- python 中執(zhí)行 linux 命令(調(diào)用 linux 命令):https://blog.csdn.net/shanliangliuxing/article/details/8811701
- (轉(zhuǎn))python 中執(zhí)行 linux 命令:https://blog.csdn.net/laiahu/article/details/6697930
- python 執(zhí)行 linux 命令的三種方式:https://zhuanlan.zhihu.com/p/100946961