Python を使用してリモート サーバーへの自動 SSH ログイン用の小さなツール コードを作成する方法 (推奨)
次のエディターは、Python を使用してリモート サーバーへの自動 SSH ログインを作成するための小さなツール (例) を提供します。編集者はこれがとても良いものだと思ったので、皆さんの参考として今から共有します。エディターをフォローして見てみましょう
多くの場合、UI インターフェイスを備えたツール領域を使用してサーバーに接続するのではなく、コンピューターの端末から直接 ssh を介して Linux サーバーに接続したいと考えます。ただし、ターミナルで ssh を使用する場合、アカウント番号とパスワードを毎回入力する必要があり、これも心配なので、Linux/Mac OS 上で動作し、リモート サーバーに自動的にログインする小さなツールを作成するだけで済みます。 SSH経由で。
GIFアニメーションの例から始めましょう:
概要
まず、必要な機能を整理しましょう:
1. それらを追加/削除します。に接続するために必要なサーバーのIP、ポート、パスワード
2. リモートサーバーにログインするためのパスワードを自動的に入力します
はい、このような簡単な機能を実行します
コードを書き始めます
コードは比較的長いので、Github と Code Cloud のアドレスも記事の最後にあります:
1 モジュール ディレクトリ osnssh (オープン ソース noob ssh) を作成し、さらに 2 つのディレクトリを作成します。以下では、1 つはメイン プログラム用で bin という名前を付け、もう 1 つは data と呼ばれるログイン データ (IP、ポート、パスワード) を保存するために使用されます。
-osnssh
-bin
-data
1. セットアッププログラム: IP、ポート、パスワードを追加/削除します。 bin/setting.py:
#!/usr/bin/env python #-*-coding:utf-8-*- import re, base64, os, sys path = os.path.dirname(os.path.abspath(sys.argv[0])) ''' 选项配置管理 author = 'allen woo' ''' def add_host_main(): while 1: if add_host(): break print("\n\nAgain:") def add_host(): ''' 添加主机信息 :return: ''' print("================Add=====================") print("[Help]Input '#q' exit") # 输入IP host_ip = str_format("Host IP:", "^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$") if host_ip == "#q": return 1 # 输入端口 host_port = str_format("Host port(Default 22):", "[0-9]+") if host_port == "#q": return 1 # 输入密码 password = str_format("Password:", ".*") if password == "#q": return 1 # 密码加密 password = base64.encodestring(password) # 输入用户名 name = str_format("User Name:", "^[^ ]+$") if name == "#q": return 1 elif not name: os.system("clear") print("[Warning]:User name cannot be emptyg") return 0 # The alias # 输入别名 alias = str_format("Local Alias:", "^[^ ]+$") if alias == "#q": return 1 elif not alias: os.system("clear") print("[Warning]:Alias cannot be emptyg") return 0 # 打开数据保存文件 of = open("{}/data/information.d".format(path)) hosts = of.readlines() # 遍历文件数据,查找是否有存在的Ip,端口,还有别名 for l in hosts: l = l.strip("\n") if not l: continue l_list = l.split(" ") if host_ip == l_list[1] and host_port == l_list[2]: os.system("clear") print("[Warning]{}:{} existing".format(host_ip, host_port)) return 0 if alias == l_list[4]: os.system("clear") print("[Warning]Alias '{}' existing".format(alias)) return 0 of.close() # save # 保存数据到数据文件 of = open("{}/data/information.d".format(path), "a") of.write("\n{} {} {} {} {}".format(name.strip("\n"), host_ip.strip("\n"), host_port, password.strip("\n"), alias.strip("\n"))) of.close() print("Add the success:{} {}@{}:{}".format(alias.strip("\n"), name.strip("\n"), host_ip.strip("\n"), host_port, password.strip("\n"))) return 1 def remove_host(): ''' 删除主机信息 :return: ''' while 1: # 打开数据文件 of = open("{}/data/information.d".format(path)) hosts = of.readlines() of.close l = len(hosts) if l <= 0: os.system("clear") print("[Warning]There is no host") return print("================Remove================") print("+{}+".format("-"*40)) print("| Alias UserName@IP:PORT") hosts_temp = [] n = 0 # 遍历输出所以信息(除了密码)供选择 for i in range(0, l): if not hosts[i].strip(): continue v_list = hosts[i].strip().split(" ") print("+{}+".format("-"*40)) print("| {} | {} {}@{}:{}".format(n+1, v_list[4], v_list[0], v_list[1], v_list[2])) n += 1 hosts_temp.append(hosts[i]) hosts = hosts_temp[:] print("+{}+".format("-"*40)) c = raw_input("[Remove]Choose the Number or Alias('#q' to exit):") is_alias = False is_y = False try: c = int(c) if c > l or c < 1: os.system("clear") print("[Warning]:There is no") continue del hosts[c-1] is_y = True except: is_alias = True if is_alias: if c.strip() == "#q": os.system("clear") break n = 0 for l in hosts: if c.strip() == l.split(" ")[4].strip(): del hosts[n] is_y = True n += 1 if not is_y: os.system("clear") print("[Warning]:There is no") continue else: # save # 再次确认是否删除 c = raw_input("Remove?[y/n]:") if c.strip().upper() == "Y": of = open("{}/data/information.d".format(path), "w") for l in hosts: of.write(l) print("Remove the success!") of.close() def str_format(lable, rule): ''' 用于验证输入的数据格式 :param lable: :param rule: :return: ''' while 1: print("{} ('#q' exit)".format(lable)) temp = raw_input().strip() m = re.match(r"{}".format(rule), temp) if m: break elif "port" in lable: temp = 22 break elif temp.strip() == "#q": os.system("clear") break os.system("clear") print("[Warning]:Invalid format") return temp
2. 設定に別の関数を追加しましょう。 py は私たちの情報、つまり私についての情報を出力するために使用されます。
def about(): ''' 输出关于这个程序的信息 :return: ''' of = open("{}/bin/about.dat".format(path)) rf = of.read() try: info = eval(rf) os.system("clear") print("================About osnssh================") for k,v in info.items(): print("{}: {}".format(k, v)) except: print("For failure.") return
次に、bin ディレクトリの下に about.dat ファイルを作成し、次のような情報を書き込みます。
{ "auther":"Allen Woo", "Introduction":"In Linux or MAC using SSH, do not need to enter the IP and password for many times", "Home page":"", "Download address":"https://github.com/osnoob/osnssh", "version":"1.1.0", "email":"xiaopingwoo@163.com" }
これで、セットアップ プログラムは次のようになります。
2.リモートサーバープログラム: auto_ssh.py という名前の py ファイルを bin に作成します:
注: ここでは、パスワードを自動的に入力するための pexpect、ユーザー端末インタラクション、インタラクション情報のキャプチャというパッケージをインストールする必要があります。
pexpect をインストールします:
pip install pexpect
それからコードを書き始めます:
#!/usr/bin/env python #-*-coding:utf-8-*- import os, sys, base64 import pexpect path = os.path.dirname(os.path.abspath(sys.argv[0])) def choose(): # 打开我们的数据文件 of = open("{}/data/information.d".format(path)) hosts = of.readlines() hosts_temp = [] for h in hosts: if h.strip(): hosts_temp.append(h) hosts = hosts_temp[:] l = len(hosts) if l <= 0: os.system("clear") print("[Warning]Please add the host server") return while 1: print("=================SSH===================") print("+{}+".format("-"*40)) print("| Alias UserName@IP:PORT") for i in range(0, l): v_list = hosts[i].strip().split(" ") print("+{}+".format("-"*40)) print("| {} | {} {}@{}:{}".format(i+1, v_list[4], v_list[0], v_list[1], v_list[2])) print("+{}+".format("-"*40)) c = raw_input("[SSH]Choose the number or alias('#q' exit):") is_alias = False is_y = False try: c = int(c) if c > l or c < 1: os.system("clear") print("[Warning]:There is no") continue l_list = hosts[c-1].split(" ") name = l_list[0] host = l_list[1] port = l_list[2] password = l_list[3] is_y = True except: is_alias = True if is_alias: if c.strip() == "#q": os.system("clear") return for h in hosts: if c.strip() == h.split(" ")[4].strip(): l_list = h.split(" ") name = l_list[0] host = l_list[1] port = l_list[2] password = l_list[3] is_y = True if not is_y: continue # ssh # 将加密保存的密码解密 password = base64.decodestring(password) print("In the connection...") # 准备远程连接,拼接ip:port print("{}@{}".format(name, host)) if port == "22": connection("ssh {}@{}".format(name, host), password) else: connection("ssh {}@{}:{}".format(name, host, port), password) def connection(cmd, pwd): ''' 连接远程服务器 :param cmd: :param pwd: :return: ''' child = pexpect.spawn(cmd) i = child.expect([".*password.*", ".*continue.*?", pexpect.EOF, pexpect.TIMEOUT]) if( i == 0 ): # 如果交互中出现.*password.*,就是叫我们输入密码 # 我们就把密码自动填入下去 child.sendline("{}\n".format(pwd)) child.interact() elif( i == 1): # 如果交互提示是否继续,一般第一次连接时会出现 # 这个时候我们发送"yes",然后再自动输入密码 child.sendline("yes\n") child.sendline("{}\n".format(pwd)) #child.interact() else: # 连接失败 print("[Error]The connection fails")
さて、あとはプログラムを開いた後の最初のメニューであるファイルを起動するだけです
3。 osnssh ディレクトリ内の osnssh.py ファイル:
#!/usr/bin/env python #-*-coding:utf-8-*- import os, sys sys.path.append("../") from bin import setting, auto_ssh path = os.path.dirname(os.path.abspath(sys.argv[0])) ''' 方便在LINUX终端使用ssh,保存使用的IP:PORT , PASSWORD 自动登录 author = 'allen woo' ''' def main(): while 1: print("==============OSNSSH [Menu]=============") print("1.Connection between a host\n2.Add host\n3.Remove host\n4.About\n[Help]: q:quit clear:clear screen") print("="*40) c = raw_input("Please select a:") if c == 1 or c == "1": auto_ssh.choose() if c == 2 or c == "2": setting.add_host_main() if c == 3 or c == "3": setting.remove_host() if c == 4 or c == "4": setting.about() elif c == "clear": os.system("clear") elif c == "q" or c == "Q" or c == "quit": print("Bye") sys.exit() else: print("\n") if name == 'main': try: of = open("{}/data/information.d".format(path)) except: of = open("{}/data/information.d".format(path), "w") of.close() main()
ついに完成したので、試してみましょう:
$python osnssh.py
以上がPython を使用してリモート サーバーへの自動 SSH ログイン用の小さなツール コードを作成する方法 (推奨)の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

numpyarraysAressertialentionsionceivationsefirication-efficientnumericalcomputations andDatamanipulation.theyarecrucialindatascience、mashineelearning、物理学、エンジニアリング、および促進可能性への適用性、scaledatiencyを効率的に、forexample、infinancialanalyyy

UseanArray.ArrayOverAlistinPythonは、Performance-criticalCode.1)homogeneousdata:araysavememorywithpedelements.2)Performance-criticalcode:Araysofterbetterbetterfornumerumerumericaleperations.3)interf

いいえ、notallistoperationSaresuptedbyarrays、andviceversa.1)arraysdonotsupportdynamicoperationslikeappendorintorintorinsertizizing、whosimpactsporformance.2)リスト

toaccesselementsinapythonlist、useindexing、negativeindexing、slicing、oriteration.1)indexingstartsat0.2)negativeindexingAcsesess.3)slicingextractStions.4)reterationSuseSuseSuseSuseSeSeS forLoopseCheckLentlentlentlentlentlentlenttodExeror。

Arraysinpython、特にvianumpy、arecrucialinscientificComputing fortheirefficienty andversitility.1)彼らは、fornumericaloperations、data analysis、andmachinelearning.2)numpy'simplementation incensuresfasteroperationsthanpasteroperations.3)arayableminablecickick

Pyenv、Venv、およびAnacondaを使用して、さまざまなPythonバージョンを管理できます。 1)Pyenvを使用して、複数のPythonバージョンを管理します。Pyenvをインストールし、グローバルバージョンとローカルバージョンを設定します。 2)VENVを使用して仮想環境を作成して、プロジェクトの依存関係を分離します。 3)Anacondaを使用して、データサイエンスプロジェクトでPythonバージョンを管理します。 4)システムレベルのタスク用にシステムPythonを保持します。これらのツールと戦略を通じて、Pythonのさまざまなバージョンを効果的に管理して、プロジェクトのスムーズな実行を確保できます。

numpyarrayshaveveraladvantages-averstandardpythonarrays:1)thealmuchfasterduetocベースのインプレンテーション、2)アレモレメモリ効率、特にlargedatasets、および3)それらは、拡散化された、構造化された形成術科療法、

パフォーマンスに対する配列の均一性の影響は二重です。1)均一性により、コンパイラはメモリアクセスを最適化し、パフォーマンスを改善できます。 2)しかし、タイプの多様性を制限し、それが非効率につながる可能性があります。要するに、適切なデータ構造を選択することが重要です。


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

Safe Exam Browser
Safe Exam Browser は、オンライン試験を安全に受験するための安全なブラウザ環境です。このソフトウェアは、あらゆるコンピュータを安全なワークステーションに変えます。あらゆるユーティリティへのアクセスを制御し、学生が無許可のリソースを使用するのを防ぎます。

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

DVWA
Damn Vulnerable Web App (DVWA) は、非常に脆弱な PHP/MySQL Web アプリケーションです。その主な目的は、セキュリティ専門家が法的環境でスキルとツールをテストするのに役立ち、Web 開発者が Web アプリケーションを保護するプロセスをより深く理解できるようにし、教師/生徒が教室環境で Web アプリケーションを教え/学習できるようにすることです。安全。 DVWA の目標は、シンプルでわかりやすいインターフェイスを通じて、さまざまな難易度で最も一般的な Web 脆弱性のいくつかを実践することです。このソフトウェアは、

EditPlus 中国語クラック版
サイズが小さく、構文の強調表示、コード プロンプト機能はサポートされていません

VSCode Windows 64 ビットのダウンロード
Microsoft によって発売された無料で強力な IDE エディター

ホットトピック









