Telnet 連接方式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
#!/usr/bin/env python # coding=utf-8 import time import telnetlib import logging __author__ = 'Evan' save_log_path = 'result.txt' file_mode = 'a+' format_info = '%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s' logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # 添加記錄 記錄器功能 fh = logging.FileHandler(save_log_path, mode = file_mode) fh.setLevel(logging.DEBUG) fh.setFormatter(logging.Formatter(format_info)) logger.addHandler(fh) # 增加顯示 記錄器功能 ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) ch.setFormatter(logging.Formatter(format_info)) logger.addHandler(ch) def telnet_handle(host = ' ', port=' '): handle = telnetlib.Telnet(host, port, timeout = 10 ) handle.set_debuglevel( 2 ) # Display connect info (send command & received info) logger.debug( 'Connect host: {} port: {} successful' . format (host, port)) try : #獲取登錄提示‘login:' 后輸入密碼。 handle.read_until( 'login:' , timeout = 5 ) #發送命令 登錄,用戶名:admin 密碼:admin handle.write( 'admin\n' ) #用戶名 #如果有輸入密碼的提示符可以打開這一條,并修正確的密碼提示符 #handle.read_until('輸入密碼提示符', timeout=5) time.sleep( 1 ) handle.write( 'admin\n' ) #密碼 time.sleep( 1 ) handle.write( 'en\n' ) #執行指令 time.sleep( 1 ) handle.write( 'sys\n' ) #執行指令 time.sleep( 1 ) handle.write( 'display running-config\n' ) #執行指令 time.sleep( 1 ) handle.write( 'show stack\n' ) #執行指令 time.sleep( 1 ) #讀取所有信息 result = handle.read_very_eager() logger.info( 'Received info: {}' . format (result)) finally : handle.close() if __name__ = = '__main__' : telnet_handle(host = '192.168.10.1' , port = '23' ) |
ssh連接方式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
#!/usr/bin/env python # coding=utf-8 import paramiko,sys,time client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #連接SSH服務器 client.connect( "192.168.10.1" , 22 , "admin" , "admin" ) #執行命令的方式一 連接linux發送固定指令 stdin,stdout,stderr = client.exec_command( "whoami" ) time.sleep( 2 ) print (stdout.read()) stdin,stdout,stderr = client.exec_command( "cat /root/lzhi/c_call_python.txt" ) print (stdout.read()) stdin,stdout,stderr = client.exec_command( "ls" ) print (stdout.read()) stdin,stdout,stderr = client.exec_command( "ls -la" ) print (stdout.read()) #執行命令的方式二 獲取命令行參數,并且刪除參數1.保留需要執行的命令 buf = sys.argv del buf[ 0 ] str1 = ' ' .join(buf) print (str1) #執行命令行參數給出的命令 stdin,stdout,stderr = client.exec_command(str1) #time.sleep(1) print (stdout.read()) |
到此這篇關于詳解python連接telnet和ssh的兩種方式的文章就介紹到這了,更多相關python連接telnet和ssh內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/github_39657856/article/details/121009899