質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

解決済

1回答

2231閲覧

Pythonライブラリnetmikoについて

riho456

総合スコア22

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

0クリップ

投稿2022/11/25 01:07

編集2022/11/25 09:37

前提

いつもお世話になっております。
ネットワーク機器(Fortigate)のCLIプロンプトをnetmikoのsend_multilineを使用して返答が出来るかの検証を行っています。FortinetSSHがsend_multilineという属性を持ち合わせてない為、出るエラーという事はわかってるのですがどこを修正すればいいのかわかりません。Python初心者のため、公式を参考にしてソースは作成しました。原因含めご教授頂けないでしょうか?send_multiline以外の他方法もありましたら情報提供よろしくお願い致します。
11/25 ソースのインデント、エラーコード修正しました。
11/25 13:55 エラーコード修正しました。
11/25 17:04 試した事修正しました。
11/25 18:26 試した事、エラーコード修正しました。

netmiko公式
https://pynet.twb-tech.com/blog/netmiko4-send-multiline.html

実現したいこと

ネットワーク機器(Fortigate)のCLIプロンプトにnetmikoを使って返答したい(他方法含め)
イメージ説明

発生している問題・エラーメッセージ

raise SSHException("No authentication methods available")
paramiko.ssh_exception.SSHException: No authentication methods available
→本文のpasswordのつづりに間違いがありました。申しわけないです。

output = net_connect.send_multiline(cmd_list)
AttributeError: 'FortinetSSH' object has no attribute 'send_multiline'
→netmikoのVerUp試した所、上記エラーは出なくなりました。

(現在のエラーコード)
cmd, expect_string = cmd_item
ValueError: not enough values to unpack (expected 2, got 1)
恐らく2つの要素が必要なのに、一つしかないという意味?cmd_list内見直し中です。

該当のソースコード

from netmiko.fortinet import FortinetSSH from netmiko import ConnectHandler device = {'device_type': 'fortinet', 'ip': '192.168.1.2', 'username': 'admin', 'password': 'Password', 'port': 22, } with ConnectHandler(**device) as net_connect: cmd_list = [ ["execute federated-upgrade initialize"], ["\n", r"immediate | hh:mm YYYY/MM/DD"], ["immediate", "\n"], ["7.2.3", "\n"], ["y", "\n"], ["n", "\n"], ["n", "\n"], ["n", "\n"], ["\n", r"confirm | cancel"], ["confirm", ""], ]  output = net_connect.send_multiline(cmd_list)  print(output) #net_connect.disconnect()

試したこと

・netmikoのVerUP 3.4.2→4.0.0
・netmikoがfortinetをサポートしている事は確認済
・print(dir(FortinetSSH))で確認。クラスがサポートしている属性の中にsend_multiineが存在しない(これが出来ない原因なのかは不明です。)

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_autodetect_fs', '_build_ssh_client', '_connect_params_dict', '_first_line_handler', '_lock_netmiko_session', '_modify_connection_params', '_open', '_read_channel', '_read_channel_expect', '_read_channel_timing', '_retrieve_output_mode', '_sanitize_output', '_test_channel_read', '_timeout_exceeded', '_try_session_preparation', '_unlock_netmiko_session', '_use_ssh_config', '_write_channel', '_write_session_log', 'check_config_mode', 'check_enable_mode', 'cleanup', 'clear_buffer', 'close_session_log', 'commit', 'config_mode', 'disable_paging', 'disconnect', 'enable', 'establish_connection', 'exit_config_mode', 'exit_enable_mode', 'find_prompt', 'is_alive', 'normalize_cmd', 'normalize_linefeeds', 'open_session_log', 'paramiko_cleanup', 'read_channel', 'read_until_pattern', 'read_until_prompt', 'read_until_prompt_or_pattern', 'run_ttp', 'save_config', 'select_delay_factor', 'send_command', 'send_command_expect', 'send_command_timing', 'send_config_from_file', 'send_config_set', 'serial_login', 'session_preparation', 'set_base_prompt', 'set_terminal_width', 'special_login_handler', 'strip_ansi_escape_codes', 'strip_backspaces', 'strip_command', 'strip_prompt', 'telnet_login', 'write_channel']

・代替案pexpect使用→通らない
(簡単にstatusを表示するコマンドが通るか確認)
公式ページ
https://pexpect.readthedocs.io/en/stable/index.html

import pexpect connection = pexpect.spawn("ssh admin@192.168.1.2") connection.expect("password:", timeout=120) connection.sendline("Password") connection.expect("FortiGate-60E#") connection.sendline("get system status")

結果、timeout?になる

raise TIMEOUT(str(err) + '\n' + str(self)) pexpect.TIMEOUT: Timeout exceeded. <pexpect.spawn object at 0x7f4b9a0e12b0> version: 3.3 command: /usr/bin/ssh args: ['/usr/bin/ssh', 'admin@192.168.1.2] searcher: <pexpect.searcher_re object at 0x7f4b92667518> buffer (last 100 chars): b' \r\nFortiGate-60E # ' before (last 100 chars): b' \r\nFortiGate-60E # ' after: <class 'pexpect.TIMEOUT'> match: None match_index: None exitstatus: None flag_eof: False pid: 3939 child_fd: 3 closed: False timeout: 30 delimiter: <class 'pexpect.EOF'> logfile: None logfile_read: None logfile_send: None maxread: 2000 ignorecase: False searchwindowsize: None delaybeforesend: 0.05 delayafterclose: 0.1 delayafterterminate: 0.1

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

melian

2022/11/25 01:33

output = net_connect.send_multiline(cmd_list) が with ConnectHandler(...) の中に入っていませんが、転記の際の書き間違いでしょうか?
riho456

2022/11/25 01:56 編集

melianさん、コメントありがとうございます。すいません、書き間違いじゃありません。中に入れる場合ってどういう記載になりますか?with ConnectHandler(**device,cmd_list)みたいな感じでしょうか?
melian

2022/11/25 02:02

はい、通常は以下の様にするかと思います。(コメント欄ですのでインデントを下げるために全角スペースを使っています) with ConnectHandler(**device) as net_connect:  cmd_list = [ :  ]  output = net_connect.send_multiline(cmd_list)  print(output) ただ、今回の問題と関係しているのかどうかは分かりません。
TakaiY

2022/11/25 03:18

melianさんの指摘は、簡単に言うと、 output = net_connect.send_multiline(cmd_list) print(output) の2行のインデントが無しになっているように見えていて、本来であれば、上のwithのブロック(cmd_list) と同じインデントになっているのではないかということです。 また、with 分なのに、closeがあるのもちょっとおかしい感じですね。
riho456

2022/11/25 03:54

melianさん、TakaiYさんアドバイスありがとうございます。 with文の意味もあまりわかってなかったので、ちょっと自分で全体をもう一度見直して修正してやってみます。
poto568

2022/11/25 04:29

「編集2022/11/25 13:06」で提示されたエラーの内容が変更されていますが 「raise SSHException("No authentication methods available")」については Fortigate側で使用するインターフェイスに対してSSHアクセスが許可されていない かもしれません。バージョン違いで見た目が違うかもしれませんが、以下ご参照 ください。 https://nwengblog.com/fortigate-mngaccess/ プログラムの問題かどうかを切り分けるために、いちど別のsshクライアントで CLIログインできるか確認してみるといいかもしれませんね。
riho456

2022/11/25 04:44

poto568さん、コメントありがとうございます。TeraTarmからSSH接続試した所、無事Fortiに接続出来ました。すいません、本文の方のpasswordのつづりが間違ってました。申し訳ないです。エラー調査中です。
TakaiY

2022/11/25 07:00

「print(dir(FortinetSSH))で確認 」の出力結果を提示していただくことできますか?
riho456

2022/11/25 08:08

TakaiYさん、お忙しい中何度もコメントありがとうございます。出力結果追記しました。
melian

2022/11/25 08:13 編集

send_multiline() は 2022/3/24 にリリースされた Netmiko 4.0.0 において追加されたメソッドなので、そちらでお使いのバージョンが 3.x なのではないでしょうか。 Release Netmiko 4.0.0 Release · ktbyers/netmiko https://github.com/ktbyers/netmiko/releases/tag/v4.0.0 > Major new features > > Add send_multiline() method
riho456

2022/11/25 08:19

melianさんお忙しい中、何度もコメントありがとうございます。netmikoのVer確認したら3.4.0でした。バージョンアップして結果確認してみます。ありがとうございます。
guest

回答1

0

自己解決

以下のpythonファイルの修正で、コマンド応答・アップデートが出来ました。
お忙しい中閲覧していた方々・コメントくださった方々、ありがとうございました。

from netmiko.fortinet import FortinetSSH from netmiko import ConnectHandler device = {'device_type': 'fortinet', 'ip': '192.168.1.2', 'username': 'admin', 'password': 'Password', 'port': 22, } with ConnectHandler(**device) as net_connect: cmd_list = [ ["execute federated-upgrade initialize", "immediate | hh:mm YYYY/MM/DD"], ["immediate", "upgraded with"], ["7.2.3", "FortiGates in upgrade"], ["y", "F"], ["n", "F"], # ["n", "F"], # ["n", "c"], ["confirm", ""], ] output = net_connect.send_multiline(cmd_list) print(output)

■実行結果(成功の場合)

execute federated-upgrade initialize Preparing for federated upgrade... When should the upgrade run? [immediate | hh:mm YYYY/MM/DD] immediate What version or version path should all FortiGates be upgraded with? (Use comma-separated versions with format M.m.p. For example, 1.2.3) 7.2.3 1 FortiGate found. Include FortiGates in upgrade? (y/n)y^J 0 FortiSwitches found. Include FortiSwitches in upgrade? (y/n) 0 FortiAPs found. Include FortiAPs in upgrade? (y/n)n^J 0 FortiExtenders found. Include FortiExtenders in upgrade? (y/n) Summary: Upgrade time: Immediate 1 FortiOS versions in path: 7.2.3 Devices to be upgraded: 1 FortiGate Please confirm the upgrade. [confirm|cancel] confirm FGT60FTK21035539 #

■実行結果(失敗の場合)
ちなみにコメントアウトをはずすとうまくいきません。この辺が釈然しませんがアップデートは出来たのでOKとします。

execute federated-upgrade initialize Preparing for federated upgrade... When should the upgrade run? [immediate | hh:mm YYYY/MM/DD] immediate What version or version path should all FortiGates be upgraded with? (Use comma-separated versions with format M.m.p. For example, 1.2.3) 7.2.3 1 FortiGate found. Include FortiGates in upgrade? (y/n)y^J 0 FortiSwitches found. Include FortiSwitches in upgrade? (y/n) 0 FortiAPs found. Include FortiAPs in upgrade? (y/n)n^J 0 FortiExtenders found. Include FortiExtenders in upgrade? (y/n) Summary: Upgrade time: Immediate 1 FortiOS versions in path: 7.2.3 Devices to be upgraded: 1 FortiGate Please confirm the upgrade. [confirm|cancel] n Upgrade cancelled. FGT60FTK21035539 # n Unknown action 0 FGT60FTK21035539 # confirm Unknown action 0 FGT60FTK21035539 #

投稿2022/11/30 00:54

編集2022/11/30 01:00
riho456

総合スコア22

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問