引数で接続するConnectHandler


検証環境

・192.168.122.19: admin/admin
・192.168.122.20: root/abc123
・192.168.122.30: SSHが設定されていない

スクリプト

from netmiko import ConnectHandler
from netmiko import NetMikoAuthenticationException
from netmiko import NetMikoTimeoutException
import getpass
import argparse

def get_arg():
    parser = argparse.ArgumentParser()

    parser.add_argument("-i", "--ipaddr",required=True, help= "IP Address you want to connect")
    parser.add_argument("-u", "--uname", default= "admin", help= "Enter your username")
    parser.add_argument("-w", "--passwd", default="admin", help = "Enter your password")
    parser.add_argument("-dev","--dev_type", default = "cisco_xe", help= "default is cisco_xe")
    parser.add_argument("-c", "--command", default="show ip int brief", help="Enter the command you want to execute")

    args = parser.parse_args()
    return args

def main():
    args = get_arg()
    try:
        conn = ConnectHandler(ip = args.ipaddr, username = args.uname, password = args.passwd, device_type = args.dev_type)
        conn.send_command("terminal length 0")
        hostname = conn.send_command("sh run | i hostname").split()[1]
        config = conn.send_command(args.command)
        print(f"Result: {args.command}, Device: {hostname}")
        print(config,"\n") 
        conn.disconnect()
    except (NetMikoAuthenticationException):
        print("Authentication Failure")
    except (NetMikoTimeoutException):
        print(f"Connecting to {args.ipaddr} Time out")

if __name__ == "__main__":
    main()

結果一覧

1) 引数なしで実行

root@*****# python3 ssh.py
usage: ssh.py [-h] -i IPADDR [-u UNAME] [-w PASSWD] [-dev DEV_TYPE] [-c COMMAND]
ssh.py: error: the following arguments are required: -i/--ipaddr

2) -hでhelpを表示

root@*****# python3 ssh.py -h
usage: ssh.py [-h] -i IPADDR [-u UNAME] [-w PASSWD] [-dev DEV_TYPE] [-c COMMAND]

optional arguments:
  -h, --help            show this help message and exit
  -i IPADDR, --ipaddr IPADDR
                        IP Address you want to connect
  -u UNAME, --uname UNAME
                        Enter your username
  -w PASSWD, --passwd PASSWD
                        Enter your password
  -dev DEV_TYPE, --dev_type DEV_TYPE
                        default is cisco_xe
  -c COMMAND, --command COMMAND
                        Enter the command you want to execute

3) IP Addressのみ引数を指定

root@*****# python3 ssh.py -i 192.168.122.19
Result: show ip int brief, Device: R19
Interface                  IP-Address      OK? Method Status                Protocol
GigabitEthernet0/0         10.19.21.19     YES NVRAM  up                    up      
GigabitEthernet0/1         10.19.29.19     YES NVRAM  up                    up      
GigabitEthernet0/2         10.19.20.19     YES NVRAM  up                    up      
GigabitEthernet0/3         unassigned      YES NVRAM  administratively down down    
GigabitEthernet0/4         unassigned      YES NVRAM  administratively down down    
GigabitEthernet0/5         100.3.19.19     YES NVRAM  up                    up      
GigabitEthernet0/6         100.6.19.19     YES NVRAM  up                    up      
GigabitEthernet0/7         unassigned      YES NVRAM  administratively down down    
Loopback0                  150.19.19.19    YES NVRAM  up                    up

デフォルトでadmin/adminのユーザネーム/パスワードなので、そのように設定されたルータであればIPアドレスの引数のみで入れる。

4) ユーザ/パスワード指定

root@*****# python3 ssh.py -i 192.168.122.20 -u root -w abc123
Result: show ip int brief, Device: R20
Interface                  IP-Address      OK? Method Status                Protocol
GigabitEthernet0/0         10.20.30.20     YES NVRAM  up                    up      
GigabitEthernet0/1         10.20.21.20     YES NVRAM  up                    up      
GigabitEthernet0/2         10.19.20.20     YES NVRAM  up                    up      
GigabitEthernet0/3         100.9.20.20     YES NVRAM  up                    up      
GigabitEthernet0/4         unassigned      YES NVRAM  administratively down down    
GigabitEthernet0/5         unassigned      YES NVRAM  administratively down down    
GigabitEthernet0/6         unassigned      YES NVRAM  administratively down down    
GigabitEthernet0/7         100.3.20.20     YES NVRAM  up                    up      
GigabitEthernet0/8         100.6.20.20     YES NVRAM  up                    up      
GigabitEthernet0/9         unassigned      YES NVRAM  administratively down down    
GigabitEthernet0/10        unassigned      YES NVRAM  administratively down down    
GigabitEthernet0/11        unassigned      YES NVRAM  administratively down down    
Loopback0                  150.20.20.20    YES NVRAM  up                    up

5) コマンドエラー(要改善)

root@*****# python3 ssh.py -i 192.168.122.19 -c show run
usage: ssh.py [-h] -i IPADDR [-u UNAME] [-w PASSWD] [-dev DEV_TYPE] [-c COMMAND]
ssh.py: error: unrecognized arguments: run

show runを1つのコマンドとして認識してくれないのでエラーを出す。
ここはどうにかしたい。

6) Authentication Failure

root@*****# python3 ssh.py -i 192.168.122.20
Authentication Failure

7) Timeout

root@*****# python3 ssh.py -i 192.168.122.30
Connecting to 192.168.122.30 Time out

知らない機能が次から次へと出てくるから楽しくて仕方がない。

参考

SR OS and Python 3 - 101

ArgumentParserの使い方を簡単にまとめた

【Python】if __name__ == ‘__main__’ とは


この記事が気に入ったらサポートをしてみませんか?