Loading... 昨天的这个时候,一个同事过来找俺。大概意思是他们做嵌入式的,正在自动化测试模块的一些功能。这个嵌入式模块会通过无线路由器连接互联网。而他们需要对这个模块所连接的无线路由器的互联网访问能力进行控制。 说了半天,俺也是听的云里雾里。最后他说他找了一根可以控制的网线。 ![2024-03-28T09:38:21.png][1] https://item.taobao.com/item.htm?abbucket=4&id=620647499054&ns=1&spm=a21n57.1.0.0.634d523cHHVZ5w 他发的图更牛逼,在网线的中间真的有一个开关灯的那种开关。看的俺眼珠子差点没掉出来。 连呼牛逼。同事可以通过在这种网线上加一个模块控制开关。然后同事就去采购了。他从OSI的物理层解决了这个需求。 思考了一天。今天尝试使用paramiko连接交换机去解决。 最后还好实现了。 ![2024-03-28T09:41:21.png][2] ``` #!/bin/env python3.7 import paramiko import time import sys # 使用示例 hostname = "xxx" username = "xxx" password = "xxx" def execute_commands_on_switch(hostname, username, password, commands): ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: ssh.connect(hostname=hostname, username=username, password=password,allow_agent=False,look_for_keys=False) shell = ssh.invoke_shell() for command in commands: shell.send(command + "\n") time.sleep(1) # 等待一段时间,让命令执行完毕 output = shell.recv(10000).decode('utf-8') print(output) except paramiko.AuthenticationException: print("Authentication failed. Please check your credentials.") except paramiko.SSHException as ssh_exception: print(f"SSH exception occurred: {ssh_exception}") finally: ssh.close() # 定义关闭接口的函数 def port_start(hostname, username, password): commands = [ "sys", "interface giga 1/0/7", "undo shutdown", "quit", "quit" ] execute_commands_on_switch(hostname, username, password, commands) # 定义恢复接口启动的函数 def port_stop(hostname, username, password): commands = [ "sys", "interface giga 1/0/7", "shutdown", "quit", "quit" ] execute_commands_on_switch(hostname, username, password, commands) if __name__ == "__main__": if len(sys.argv) > 1: action = sys.argv[1] if action == 'start': port_start(hostname,username,password) elif action == 'stop': port_stop(hostname,username,password) else: print("Invalid argument, please specify 'start' or 'stop'") else: print("No action specified, please provide an argument (either 'start' or 'stop')") ``` [1]: https://www.sddts.cn/usr/uploads/2024/03/201102331.png [2]: https://www.sddts.cn/usr/uploads/2024/03/1923630213.png 最后修改:2024 年 05 月 11 日 © 允许规范转载 赞 如果觉得我的文章对你有用,请随意赞赏