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('
'))
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')
pycryptは、paramikoモジュールの内部依存性pycryptのため、ダウンロードしてpycryptをインストールします。
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!"
以上のスクリプトは2つのパラメータを読み、最初はIPを格納するテキスト、2番目は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命令に関する資料は他の関連記事に注目してください。