最近想要实现通过脚本循环再Linux下运行shell命令,经过探索发现使用Python语言有几种解决方案,在此简单记录。
方案一:脚本本地执行命令
在Python中有两个库都可以实现运行shell命令的效果:import subprocess
import os
使用方法也很简单:# subprocess 使用方法
subprocess.call("ls") # 执行ls命令
# os 使用方法
# 使用system模块执行linux命令时,如果执行的命令没有返回值res的值是256
# 如果执行的命令有返回值且成功执行,返回值是0
res = os.system("ls")
# popen模块执行linux命令。返回值是类文件对象,获取结果要采用read()或者readlines()
val = os.popen('ls').read() # 执行结果包含在val中
方案二:脚本远程执行命令
在 Python 中有一个库可以实现SSH客户端及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
# 运行命令
def ssh_exec_cmd( _ssh_fd, _cmd ):
return _ssh_fd.exec_command( _cmd )
# 关闭SSH
def ssh_close( _ssh_fd ):
_ssh_fd.close()
方案三:使用SecureCRT脚本
参考文献
---------------------
Author: Frytea
Title: Python执行或远程执行shell命令
Link: https://blog.frytea.com/archives/471/
Copyright: This work by TL-Song is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.