2025年3月24日 星期一 甲辰(龙)年 月廿三 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > Python

Python执行或远程执行shell命令

时间:10-30来源:作者:点击数:55

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

该方法参见此前的文章:SecureCRT 下 Python 脚本编写

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门