def run_gevent(ip_list): issue_device = [] try: hwconfig = get_config(ip_list) write_config_to_file(hwconfig,ip_list) except (AuthenticationException): issue_message = (ip_list + ': 认证错误 ') issue_device.append(issue_message) except NetMikoTimeoutException: issue_message = (ip_list + ': 网络不可达 ') issue_device.append(issue_message) except (SSHException): issue_message = (ip_list +': SSH端口异常 ') issue_device.append(issue_message) except Exception as unknown_error: issue_message = (ip_list +': 发生未知错误: ') issue_device.append(issue_message+str(unknown_error)) finally: write_issue_device(issue_device) def main(): starting_time = time() ip_list = read_device_excel() pool = Pool(50) pool.map(run_gevent,ip_list) #map(func, iterable) pool.join() print ('\n---- End get config threading, elapsed time=', time() - starting_time) 这里之前会产生报错TypeError: can only concatenate tuple (not "str") to tuple请问如何修改,其中ip_list.append((ipaddr,ntos,name,pswd,epswd))
时间: 2023-12-27 15:02:54 浏览: 125
这个错误是因为你在以下代码中尝试将字符串和元组连接:
```
issue_device.append(issue_message+str(unknown_error))
```
要解决这个问题,可以将 `issue_message` 从字符串转换为元组:
```
issue_message = (ip_list +': 发生未知错误: ',)
```
然后在连接时使用元组:
```
issue_device.append(issue_message + (str(unknown_error),))
```
这应该可以解决报错问题。关于另一个问题,如果你想将 `(ipaddr, ntos, name, pswd, epswd)` 添加到 `ip_list` 中,你可以使用以下代码:
```
ip_list.append((ipaddr, ntos, name, pswd, epswd))
```
这将把这个元组添加到 `ip_list` 中。
相关问题
#!/usr/bin/env python #coding: utf-8 import os from time import time from datetime import datetime from netmiko import ConnectHandler from openpyxl import Workbook from openpyxl import load_workbook def read_device_excel( ): ip_list = [] wb1 = load_workbook('E:\/Users/Wayne_Peng/Desktop/cs_lab.xlsx') ws1 = wb1.get_sheet_by_name("Sheet1") for cow_num in range(2,ws1.max_row+1): ipaddr = ws1["a"+str(cow_num)].value ip_list.append(ipaddr) return ip_list def get_config(ipaddr): session = ConnectHandler(device_type="huawei", ip=ipaddr, username="mtlops", password="cisco,123", banner_timeout=300) print("connecting to "+ ipaddr) print ("---- Getting HUAWEI configuration from {}-----------".format(ipaddr)) # config_data = session.send_command('screen-length 0 temporary') # config_data = session.send_command('dis cu | no-more ') # command = 'display version | display cpu-usage | display memory-usage' # config_data = session.send_command(command) commands = ['display version', 'display cpu-usage', 'display memory-usage'] config_data = '' for cmd in commands: output = session.send_command_timing(cmd) config_data += f'{cmd}\n{output}\n' session.disconnect() return config_data def write_config_to_file(config_data,ipaddr): now = datetime.now() date= "%s-%s-%s"%(now.year,now.month,now.day) time_now = "%s-%s"%(now.hour,now.minute) #---- Write out configuration information to file config_path = 'E:\/Users/Wayne_Peng/Desktop/' +date verify_path = os.path.exists(config_path) if not verify_path: os.makedirs(config_path) config_filename = config_path+"/"+'config_' + ipaddr +"_"+date+"_" + time_now # Important - create unique configuration file name print ('---- Writing configuration: ', config_filename) with open( config_filename, "w",encoding='utf-8' ) as config_out: config_out.write( config_data ) return def main(): starting_time = time() ip_list = read_device_excel() for ipaddr in ip_list: hwconfig = get_config(ipaddr) write_config_to_file(hwconfig,ipaddr) print ('\n---- End get config threading, elapsed time=', time() - starting_time) #======================================== # Get config of HUAWEI #======================================== if __name__ == '__main__': main() 加一段gevent,def run_gevent()
好的,可以尝试这样写:
```
#!/usr/bin/env python
#coding: utf-8
import os
from time import time
from datetime import datetime
from netmiko import ConnectHandler
from openpyxl import Workbook
from openpyxl import load_workbook
import gevent
from gevent import monkey
monkey.patch_all()
def read_device_excel():
ip_list = []
wb1 = load_workbook('E:\/Users/Wayne_Peng/Desktop/cs_lab.xlsx')
ws1 = wb1.get_sheet_by_name("Sheet1")
for cow_num in range(2,ws1.max_row+1):
ipaddr = ws1["a"+str(cow_num)].value
ip_list.append(ipaddr)
return ip_list
def get_config(ipaddr):
session = ConnectHandler(device_type="huawei",
ip=ipaddr,
username="mtlops",
password="cisco,123",
banner_timeout=300)
print("connecting to "+ ipaddr)
print ("---- Getting HUAWEI configuration from {}-----------".format(ipaddr))
commands = ['display version', 'display cpu-usage', 'display memory-usage']
config_data = ''
for cmd in commands:
output = session.send_command_timing(cmd)
config_data += f'{cmd}\n{output}\n'
session.disconnect()
return config_data
def write_config_to_file(config_data,ipaddr):
now = datetime.now()
date= "%s-%s-%s"%(now.year,now.month,now.day)
time_now = "%s-%s"%(now.hour,now.minute)
#---- Write out configuration information to file
config_path = 'E:\/Users/Wayne_Peng/Desktop/' +date
verify_path = os.path.exists(config_path)
if not verify_path:
os.makedirs(config_path)
config_filename = config_path+"/"+'config_' + ipaddr +"_"+date+"_" + time_now # Important - create unique configuration file name
print ('---- Writing configuration: ', config_filename)
with open( config_filename, "w",encoding='utf-8' ) as config_out:
config_out.write( config_data )
return
def run_gevent(ip_list):
jobs = []
for ipaddr in ip_list:
jobs.append(gevent.spawn(get_config, ipaddr))
gevent.joinall(jobs)
for job, ipaddr in zip(jobs, ip_list):
hwconfig = job.value
write_config_to_file(hwconfig,ipaddr)
print('\n---- End get config threading')
def main():
starting_time = time()
ip_list = read_device_excel()
run_gevent(ip_list)
print('elapsed time:', time() - starting_time)
#========================================
# Get config of HUAWEI
#========================================
if __name__ == '__main__':
main()
```
注意,这里使用了 `gevent` 库,需要先安装。可以在命令行中使用 `pip install gevent` 进行安装。
import asyncio,aiohttp,aiofiles,os from gevent import monkey from bs4 import BeautifulSoup import nest_asyncio nest_asyncio.apply() class VoaCrawler: def __init__(self, url): self.url = url async def fetch_mp3_urls(self, page_url): async with aiohttp.ClientSession() as session: async with session.get(page_url) as response: html = await response.text() soup = BeautifulSoup(html, 'html.parser') mp3_urls = [] for link in soup.find_all('a'): href = link.get('href') if href and href.endswith('.mp3'): mp3_urls.append(href) self.mp3_urls=mp3_urls async def download_mp3(self): async for mp3_url in self.mp3_urls: async with aiohttp.ClientSession() as session: async with session.get(mp3_url) as resp: os.chdir("/Users/lihanjing/Desktop/python/每周作业/作业week13/vedios") if resp.status == 200: async with aiofiles.open(mp3_url.split('/')[-1], mode='wb') as f: await f.write(await resp.content.read()) crawler = VoaCrawler('https://www.51voa.com/VOA_Standard_3.html') loop=asyncio.get_event_loop() tasks= [loop.create_task(crawler.fetch_mp3_urls(5)),loop.create_task(crawler.download_mp3())] loop.run_until_complete(asyncio.wait(tasks)) loop.close()
这段代码是一个使用异步编程方式爬取VOA网站的mp3文件链接并下载到本地的爬虫程序。它使用了Python中的asyncio模块和aiohttp库来实现异步HTTP请求和异步文件读写操作。具体来说,它定义了一个VoaCrawler类,其中包含fetch_mp3_urls和download_mp3两个异步方法,前者用于从VOA网站获取mp3文件链接,后者用于将这些链接对应的文件下载到本地。在主函数中,它创建了一个VoaCrawler对象,并使用asyncio模块创建了两个任务,并通过run_until_complete方法启动了这两个任务的执行,从而实现了异步爬取和下载。
阅读全文