python ssh 执行shell命令的示例

# -*- coding: utf-8 -*-

import paramiko
import threading

def run(host_ip, username, password, command):
  ssh = paramiko.SSHClient()
  try:
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(host_ip, 22, username, password)

    print('===================exec on [%s]=====================' % host_ip)

    stdin, stdout, stderr = ssh.exec_command(command, timeout=300)
    out = stdout.readlines()
  for o in out:
      print (o.strip('\n'))
  except Exception as ex:
    print('error, host is [%s], msg is [%s]' % (host_ip, ex.message))
  finally:
    ssh.close()

if __name__ == '__main__':

  # 将需要批量执行命令的host ip地址填到这里
  # eg: host_ip_list = ['IP1', 'IP2']

  host_ip_list = ['147.116.20.19']
  for _host_ip in host_ip_list:

    # 用户名,密码,执行的命令填到这里
    run(_host_ip, 'tzgame', 'tzgame@1234', 'df -h')
    run(_host_ip, 'tzgame', 'tzgame@1234', 'ping -c 5 220.181.38.148')

pycrypto,由于 paramiko 模块内部依赖pycrypto,所以先下载安装pycrypto

pip3 install pycrypto
pip3 install paramiko

(1)基于用户名和密码的连接

import paramiko

# 创建SSH对象
ssh = paramiko.SSHClient()

# 允许连接不在know_hosts文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# 连接服务器
ssh.connect(hostname='c1.salt.com', port=22, username='GSuser', password='123')

# 执行命令
stdin, stdout, stderr = ssh.exec_command('ls')

# 获取命令结果
result = stdout.read()

# 关闭连接
ssh.close()

(2)基于公钥秘钥连接

import paramiko

private_key = paramiko.RSAKey.from_private_key_file('/home/auto/.ssh/id_rsa')

# 创建SSH对象
ssh = paramiko.SSHClient()

# 允许连接不在know_hosts文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# 连接服务器
ssh.connect(hostname='c1.salt.com', port=22, username='wupeiqi', key=private_key)

# 执行命令
stdin, stdout, stderr = ssh.exec_command('df')

# 获取命令结果
result = stdout.read()

# 关闭连接
ssh.close()

SFTPClient:

  用于连接远程服务器并进行上传下载功能。

(1)基于用户名密码上传下载

import paramiko

transport = paramiko.Transport(('hostname',22))
transport.connect(username='GSuser',password='123')

sftp = paramiko.SFTPClient.from_transport(transport)

# 将location.py 上传至服务器 /tmp/test.py
sftp.put('/tmp/location.py', '/tmp/test.py')

# 将remove_path 下载到本地 local_path
sftp.get('remove_path', 'local_path')

transport.close()

(2)基于公钥秘钥上传下载

import paramiko

private_key = paramiko.RSAKey.from_private_key_file('/home/auto/.ssh/id_rsa')

transport = paramiko.Transport(('hostname', 22))
transport.connect(username='GSuser', pkey=private_key )

sftp = paramiko.SFTPClient.from_transport(transport)

# 将location.py 上传至服务器 /tmp/test.py
sftp.put('/tmp/location.py', '/tmp/test.py')

# 将remove_path 下载到本地 local_path
sftp.get('remove_path', 'local_path')

transport.close()

下面是多线程执行版本

#!/usr/bin/python
#coding:utf-8
import threading
import subprocess
import os
import sys

sshport = 13131
log_path = 'update_log'
output = {}

def execute(s, ip, cmd, log_path_today):
  with s:
    cmd = '''ssh -p%s root@%s -n "%s" ''' % (sshport, ip, cmd)

    ret = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    output[ip] = ret.stdout.readlines()

if __name__ == "__main__":
  if len(sys.argv) != 3:
    print "Usage: %s config.ini cmd" % sys.argv[0]
    sys.exit(1)

  if not os.path.isfile(sys.argv[1]):
    print "Usage: %s is not file!" % sys.argv[1]
    sys.exit(1)

  cmd = sys.argv[2]

  f = open(sys.argv[1],'r')
  list = f.readlines()
  f.close()
  today = datetime.date.today()
  log_path_today = '%s/%s' % (log_path,today)
  if not os.path.isdir(log_path_today):
    os.makedirs(log_path_today)

  threading_num = 100
  if threading_num > len(list):
    threading_num = len(list)

  s = threading.Semaphore(threading_num)

  for line in list:
    ip = line.strip()
    t = threading.Thread(target=execute,args=(s, ip,cmd,log_path_today))
    t.setDaemon(True)
    t.start()

  main_thread = threading.currentThread()
  for t in threading.enumerate():
    if t is main_thread:
      continue
    t.join()

  for ip,result in output.items():
    print "%s: " % ip
    for line in result:
      print "  %s" % line.strip()

  print "Done!"

以上脚本读取两个参数,第一个为存放IP的文本,第二个为shell命令

执行效果如下

# -*- coding:utf-8 -*-
import requests
from requests.exceptions import RequestException
import os, time
import re
from lxml import etree
import threading

lock = threading.Lock()
def get_html(url):

  response = requests.get(url, timeout=10)
  # print(response.status_code)
  try:
    if response.status_code == 200:

      # print(response.text)
      return response.text
    else:
       return None
  except RequestException:
    print("请求失败")
    # return None

def parse_html(html_text):

  html = etree.HTML(html_text)

  if len(html) > 0:
    img_src = html.xpath("//img[@class='photothumb lazy']/@data-original") # 元素提取方法
    # print(img_src)
    return img_src

  else:
    print("解析页面元素失败")

def get_image_pages(url):
  html_text = get_html(url) # 获取搜索url响应内容
  # print(html_text)
  if html_text is not None:
    html = etree.HTML(html_text) # 生成XPath解析对象
    last_page = html.xpath("//div[@class='pages']//a[last()]/@href") # 提取最后一页所在href链接
    print(last_page)
    if last_page:
      max_page = re.compile(r'(\d+)', re.S).search(last_page[0]).group() # 使用正则表达式提取链接中的页码数字
      print(max_page)
      print(type(max_page))
      return int(max_page) # 将字符串页码转为整数并返回
    else:
      print("暂无数据")
      return None
  else:
    print("查询结果失败")

def get_all_image_url(page_number):
  base_url = 'https://imgbin.com/free-png/naruto/'
  image_urls = []

  x = 1 # 定义一个标识,用于给每个图片url编号,从1递增
  for i in range(1, page_number):
    url = base_url + str(i) # 根据页码遍历请求url
    try:
      html = get_html(url) # 解析每个页面的内容
      if html:
        data = parse_html(html) # 提取页面中的图片url
        # print(data)
        # time.sleep(3)
        if data:
          for j in data:
            image_urls.append({
              'name': x,
              'value': j
            })
            x += 1 # 每提取一个图片url,标识x增加1
    except RequestException as f:
      print("遇到错误:", f)
      continue
  # print(image_urls)
  return image_urls

def get_image_content(url):
  try:
    r = requests.get(url, timeout=15)
    if r.status_code == 200:
      return r.content
    return None
  except RequestException:
    return None

def main(url, image_name):
  semaphore.acquire() # 加锁,限制线程数
  print('当前子线程: {}'.format(threading.current_thread().name))
  save_path = os.path.dirname(os.path.abspath('.')) + '/pics/'
  try:
    file_path = '{0}/{1}.jpg'.format(save_path, image_name)
    if not os.path.exists(file_path): # 判断是否存在文件,不存在则爬取
      with open(file_path, 'wb') as f:
        f.write(get_image_content(url))
        f.close()

        print('第{}个文件保存成功'.format(image_name))

    else:
      print("第{}个文件已存在".format(image_name))

    semaphore.release() # 解锁imgbin-多线程-重写run方法.py

  except FileNotFoundError as f:
    print("第{}个文件下载时遇到错误,url为:{}:".format(image_name, url))
    print("报错:", f)
    raise

  except TypeError as e:
    print("第{}个文件下载时遇到错误,url为:{}:".format(image_name, url))
    print("报错:", e)

class MyThread(threading.Thread):
  """继承Thread类重写run方法创建新进程"""
  def __init__(self, func, args):
    """

    :param func: run方法中要调用的函数名
    :param args: func函数所需的参数
    """
    threading.Thread.__init__(self)
    self.func = func
    self.args = args

  def run(self):
    print('当前子线程: {}'.format(threading.current_thread().name))
    self.func(self.args[0], self.args[1])
    # 调用func函数
    # 因为这里的func函数其实是上述的main()函数,它需要2个参数;args传入的是个参数元组,拆解开来传入

if __name__ == '__main__':
  start = time.time()
  print('这是主线程:{}'.format(threading.current_thread().name))

  urls = get_all_image_url(5) # 获取所有图片url列表
  thread_list = [] # 定义一个列表,向里面追加线程
  semaphore = threading.BoundedSemaphore(5) # 或使用Semaphore方法
  for t in urls:
    # print(i)

    m = MyThread(main, (t["value"], t["name"])) # 调用MyThread类,得到一个实例

    thread_list.append(m)

  for m in thread_list:

    m.start() # 调用start()方法,开始执行

  for m in thread_list:
    m.join() # 子线程调用join()方法,使主线程等待子线程运行完毕之后才退出

  end = time.time()
  print(end-start)
  # get_image_pages(https://imgbin.com/free-png/Naruto)

以上就是python ssh 执行shell命令的示例的详细内容,更多关于python ssh 执行shell命令的资料请关注我们其它相关文章!

(0)

相关推荐

  • python实现ssh及sftp功能(实例代码)

    1.在Linux上我们通过scp命令实现主机间的文件传送,通过ssh实现远程登录 ,比如 我们经常使用的xshell远程登录工具,就是基础ssh协议实现window主机远程登录Linux主机 下面简单的在python实现这几个功能   下面使用到paramiko模块,这个不是python的内置模块,我直接通过pycharm下载这个模块, 第一步实现一个简单的ssh登录命令 代码如下: import paramiko # 创建SSH对象 ssh = paramiko.SSHClient() # 允

  • python使用paramiko实现ssh的功能详解

    个人认为python的paramiko模块是运维人员必学模块之一,其ssh登录功能是旅行居家必备工具. 安装paramiko很简单,pip install paramiko就搞定了,其依赖库会被一并安装. paramiko的官方站点在这里:http://www.paramiko.org/.有需要深入研究的可以阅读官方文档. paramiko模块提供了ssh及sft进行远程登录服务器执行命令和上传下载文件的功能. 一.基于用户名和密码的 sshclient 方式登录 # 建立一个sshclient

  • python通过ssh-powershell监控windows的方法

    本文实例讲述了python通过ssh-powershell监控windows的方法.分享给大家供大家参考.具体分析如下: 对于服务器的监控来说,监控linux不管是自己动手写脚本还是用一些开源的工具比如nagios,zenoss什么的.但毕竟还是有些公司有windows做服务器的,相对linux来说,windows没有方便的shell,cmd下提供的命令对于监控来说远远没有linux方便.但是现在windows上如果安装了powershell(win7,2008自带),就比以前方便多了,linu

  • python SSH模块登录,远程机执行shell命令实例解析

    用python SSH模块登录,并在远程机执行shell命令 (在CentOS 7 环境试验成功, Redhat 系列应该是兼容的.) 先安装必须的模块 # yum install python-dev # yum install python-devel # pip install pycrypto # pip install paramiko # pip install ssh 这些都成功后, 编写一个Python脚本 # vim remote_run.py import ssh # 新建一

  • Python基于模块Paramiko实现SSHv2协议

    简介: ssh是一个协议,OpenSSH是其中一个开源实现,paramiko是Python的一个库,实现了SSHv2协议(底层使用cryptography). 有了Paramiko以后,我们就可以在Python代码中直接使用SSH协议对远程服务器执行操作,而不是通过ssh命令对远程服务器进行操作. 由于paramiko属于第三方库,所以需要使用如下命令先行安装 :pip install paramiko paramiko包含两个核心组件:SSHClient和SFTPClient. SSHClie

  • 使用 Python ssh 远程登陆服务器的最佳方案

    在使用 Python 写一些脚本的时候,在某些情况下,我们需要频繁登陆远程服务去执行一次命令,并返回一些结果. 在 shell 环境中,我们是这样子做的. $ sshpass -p ${passwd} ssh -p ${port} -l ${user} -o StrictHostKeyChecking=no xx.xx.xx.xx "ls -l" 然后你会发现,你的输出有很多你并不需要,但是又不去不掉的一些信息(也许有方法,请留言交流),类似这样 host: xx.xx.xx.xx,

  • 解决Python paramiko 模块远程执行ssh 命令 nohup 不生效的问题

    Python - paramiko 模块远程执行ssh 命令 nohup 不生效的问题解决 1.使用 paramiko 模块ssh 登陆到 linux 执行nohup命令不生效 # 执行命令 def command(ssh_config, cmd, result_print=None, nohup=False): ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.con

  • python获取交互式ssh shell的方法

    更新,最近在学unix环境编程,了解一下进程的创建过程,用最原始的方式实现了一个ssh命令的执行. #coding=utf8 ''' 用python实现了一个简单的shell,了解进程创建 类unix 环境下 fork和exec 两个系统调用完成进程的创建 ''' import sys, os def myspawn(cmdline): argv = cmdline.split() if len(argv) == 0: return program_file = argv[0] pid = os

  • python ssh 执行shell命令的示例

    # -*- coding: utf-8 -*- import paramiko import threading def run(host_ip, username, password, command): ssh = paramiko.SSHClient() try: ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(host_ip, 22, username, password) print('====

  • C++/Php/Python 语言执行shell命令的方法(推荐)

    编程中经常需要在程序中使用shell命令来简化程序,这里记录一下. 1. C++ 执行shell命令 #include <iostream> #include <string> #include <stdio.h> int exec_cmd(std::string cmd, std::string &res){ if (cmd.size() == 0){ //cmd is empty return -1; } char buffer[1024] = {0}; s

  • python中执行shell命令的几个方法小结

    最近有个需求就是页面上执行shell命令,第一想到的就是os.system, 复制代码 代码如下: os.system('cat /proc/cpuinfo') 但是发现页面上打印的命令执行结果 0或者1,当然不满足需求了. 尝试第二种方案 os.popen() 复制代码 代码如下: output = os.popen('cat /proc/cpuinfo') print output.read() 通过 os.popen() 返回的是 file read 的对象,对其进行读取 read() 的

  • python 执行shell命令并将结果保存的实例

    方法1: 将shell执行的结果保存到字符串 def run_cmd(cmd): result_str='' process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) result_f = process.stdout error_f = process.stderr errors = error_f.read() if errors: pass result_str =

  • 解决python 执行shell命令无法获取返回值的问题

    问题背景:利用python获取服务器中supervisor状态信息时发现未能获取到返回值. python获取执行shell命令后返回值得几种方式: # 1.os模块 ret = os.popen("supervisorctl status") ret_data = ret.read() # 2.subprocess模块 ret = subprocess.Popen('supervisorctl status',shell=True,stdout=subprocess.PIPE) out

  • 对python中执行DOS命令的3种方法总结

    1. 使用os.system("cmd") 特点是执行的时候程序会打出cmd在Linux上执行的信息. import os os.system("ls") 2. 使用Popen模块产生新的process 现在大部分人都喜欢使用Popen.Popen方法不会打印出cmd在linux上执行的信息.的确,Popen非常强大,支持多种参数和模式.使用前需要from subprocess import Popen, PIPE.但是Popen函数有一个缺陷,就是它是一个阻塞的方

  • java通过ssh连接服务器执行shell命令详解及实例

    java通过ssh连接服务器执行shell命令详解 java通过ssh连接服务器执行shell命令:JSch 是SSH2的一个纯Java实现.它允许你连接到一个sshd 服务器,使用端口转发,X11转发,文件传输等等.你可以将它的功能集成到你自己的 程序中.同时该项目也提供一个J2ME版本用来在手机上直连SSHD服务器. SSH是Secure Shell的缩写,一种建立在应用层和传输层基础上的安全协议.SSH在连接和传送过程中会加密所有数据,可以用来在不同系统或者服务器之间进行安全连接.SSH提

  • 基于Java实现ssh命令登录主机执行shell命令过程解析

    这篇文章主要介绍了基于Java实现ssh命令登录主机执行shell命令过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.SSH命令 SSH 为 Secure Shell的缩写,由 IETF 的网络小组(Network Working Group)所制定:SSH 为建立在应用层基础上的安全协议.SSH 是较可靠,专为远程登录会话和其他网络服务提供安全性的协议.利用 SSH 协议可以有效防止远程管理过程中的信息泄露问题.SSH最初是UNI

  • Python使用paramiko连接远程服务器执行Shell命令的实现

    需求 在自动化测试场景里, 有时需要在代码里获取远程服务器的某些数据, 或执行一些查询命令,如获取Linux系统版本号 \ 获取CPU及内存的占用等, 本章记录一下使用paramiko模块SSH连接服务器的方法 1. 先安装paramiko库 pip3 install paramiko 2. 代码 #!/usr/bin/env python # coding=utf-8 """ # :author: Terry Li # :url: https://blog.csdn.net

随机推荐