最近想要实现通过脚本循环再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 下 Python 脚本编写