电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術文章
文章詳情頁

python ssh 執行shell命令的示例

瀏覽:41日期:2022-07-09 14:33:02

# -*- coding: utf-8 -*-import paramikoimport threadingdef 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 pycryptopip3 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 paramikoprivate_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 paramikotransport = paramiko.Transport((’hostname’,22))transport.connect(username=’GSuser’,password=’123’)sftp = paramiko.SFTPClient.from_transport(transport)# 將location.py 上傳至服務器 /tmp/test.pysftp.put(’/tmp/location.py’, ’/tmp/test.py’)# 將remove_path 下載到本地 local_pathsftp.get(’remove_path’, ’local_path’)transport.close()

(2)基于公鑰秘鑰上傳下載

import paramikoprivate_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.pysftp.put(’/tmp/location.py’, ’/tmp/test.py’)# 將remove_path 下載到本地 local_pathsftp.get(’remove_path’, ’local_path’)transport.close()

下面是多線程執行版本

#!/usr/bin/python#coding:utf-8import threadingimport subprocessimport osimport syssshport = 13131log_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命令

執行效果如下

python ssh 執行shell命令的示例

# -*- coding:utf-8 -*-import requestsfrom requests.exceptions import RequestExceptionimport os, timeimport refrom lxml import etreeimport threadinglock = 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 Nonedef 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_urlsdef get_image_content(url): try: r = requests.get(url, timeout=15) if r.status_code == 200: return r.content return None except RequestException: return Nonedef 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命令的資料請關注好吧啦網其它相關文章!

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 济南电缆桥架|山东桥架-济南航丰实业有限公司 | 水质监测站_水质在线分析仪_水质自动监测系统_多参数水质在线监测仪_水质传感器-山东万象环境科技有限公司 | 防爆电机-高压防爆电机-ybx4电动机厂家-河南省南洋防爆电机有限公司 | 陕西视频监控,智能安防监控,安防系统-西安鑫安5A安防工程公司 | 搅拌磨|搅拌球磨机|循环磨|循环球磨机-无锡市少宏粉体科技有限公司 | 高低温万能试验机-复合材料万能试验机-馥勒仪器 | 苏州西装定制-西服定制厂家-职业装定制厂家-尺品服饰西装定做公司 | 精密钢管,冷拔精密无缝钢管,精密钢管厂,精密钢管制造厂家,精密钢管生产厂家,山东精密钢管厂家 | 北京开业庆典策划-年会活动策划公司-舞龙舞狮团大鼓表演-北京盛乾龙狮鼓乐礼仪庆典策划公司 | 留学生辅导网-在线课程论文辅导-留学生挂科申诉机构 | 电子厂招聘_工厂招聘_普工招聘_小时工招聘信息平台-众立方招工网 | 煤粉取样器-射油器-便携式等速飞灰取样器-连灵动 | 污水处理设备维修_污水处理工程改造_机械格栅_过滤设备_气浮设备_刮吸泥机_污泥浓缩罐_污水处理设备_污水处理工程-北京龙泉新禹科技有限公司 | 东莞动力锂电池保护板_BMS智能软件保护板_锂电池主动均衡保护板-东莞市倡芯电子科技有限公司 | TTCMS自助建站_网站建设_自助建站_免费网站_免费建站_天天向上旗下品牌 | 洁净化验室净化工程_成都实验室装修设计施工_四川华锐净化公司 | 鼓风干燥箱_真空烘箱_高温干燥箱_恒温培养箱-上海笃特科学仪器 | 厂房出租_厂房出售_产业园区招商_工业地产 - 中工招商网 | 定制液氮罐_小型气相液氮罐_自增压液氮罐_班德液氮罐厂家 | 丁基胶边来料加工,医用活塞边角料加工,异戊二烯橡胶边来料加工-河北盛唐橡胶制品有限公司 | 不锈钢/气体/液体玻璃转子流量计(防腐,选型,规格)-常州天晟热工仪表有限公司【官网】 | 屏蔽服(500kv-超高压-特高压-电磁)-徐吉电气| 动力配电箱-不锈钢配电箱-高压开关柜-重庆宇轩机电设备有限公司 聚天冬氨酸,亚氨基二琥珀酸四钠,PASP,IDS - 远联化工 | 万家财经_财经新闻_在线财经资讯网 | 电位器_轻触开关_USB连接器_广东精密龙电子科技有限公司 | PVC快速门-硬质快速门-洁净室快速门品牌厂家-苏州西朗门业 | 在线悬浮物浓度计-多参数水质在线检测仪-上海沃懋仪表科技有限公司 | 二氧化碳/活性炭投加系统,次氯酸钠发生器,紫外线消毒设备|广州新奥 | 深圳公司注册-工商注册代理-注册公司流程和费用_护航财税 | 储能预警-储能消防系统-电池舱自动灭火装置-四川千页科技股份有限公司官网 | 智能案卷柜_卷宗柜_钥匙柜_文件流转柜_装备柜_浙江福源智能科技有限公司 | 湖南专升本-湖南省专升本报名-湖南统招专升本考试网 | 国产液相色谱仪-超高效液相色谱仪厂家-上海伍丰科学仪器有限公司 | 上海办公室装修公司_办公室设计_直营办公装修-羚志悦装 | 安徽千住锡膏_安徽阿尔法锡膏锡条_安徽唯特偶锡膏_卡夫特胶水-芜湖荣亮电子科技有限公司 | 卫生纸复卷机|抽纸机|卫生纸加工设备|做卫生纸机器|小型卫生纸加工需要什么设备|卫生纸机器设备多少钱一台|许昌恒源纸品机械有限公司 | 百度爱采购运营研究社社群-店铺托管-爱采购代运营-良言多米网络公司 | 工业机械三维动画制作 环保设备原理三维演示动画 自动化装配产线三维动画制作公司-南京燃动数字 聚合氯化铝_喷雾聚氯化铝_聚合氯化铝铁厂家_郑州亿升化工有限公司 | 湖南自考_湖南自学考试网| 硫化罐_蒸汽硫化罐_大型硫化罐-山东鑫泰鑫智能装备有限公司 | 小型高低温循环试验箱-可程式高低温湿热交变试验箱-东莞市拓德环境测试设备有限公司 |