(Simon Tatham,1977-)
不知道為什麼世界上就是有人喜歡破壞與入侵別人的系統. 導致大家都使用 Putty 等 ssh 加密的東西連線, 或許你的機器也必須用 telnet/ssh client 才能連線.
為了因應這種系統, 在 Python 下你不能使用 telnet class 進行連線, 但你可以使用 Simon Tatham 先生寫的 plink.exe (Putty 命令列版), 安全地做你想作的事.
在 Python 下整件事很簡單, 只要用 os.system 下指令即可完成.
關鍵是 plink.exe 的使用方式, 別擔心只有一行. ^_^
首先下載 plink.exe (Putty 的命令列版本)
plink 的簡易教學
使用 ssh telnet 連線
c:\plink -ssh login.example.com
login as:
自動連上(包含 username 與 passwd)
在遠端機器上, 批次執行一堆指令c:\plink -ssh login.example.com -l(空格)名字 -pw(空格)密碼
c:\plink -ssh login.example.com -l(空格)名字 -pw(空格)密碼 命令1;命令2
ex:
c:\plink -ssh login.example.com -l(空格)名字 -pw(空格)密碼 ls;echo Hello World;ls
現在你已經具備在遠端進行批次工作的知識了.
Python 的部分
其實現在不用 Python 這種東西, 直接用 Dos Prompt 就可以了,
為了表示我們可以用 Python , 進行批次處理. 所以我寫了一個範例.
下面是 Python 搭配 plink 進行遠端 ssh 批次處理的 code
import os
host="192.168.0.1"
user="username"
passwd="passwd"
com_array=["cd ~jing",
"ls -la",
"ftpget -u jing -p passwd ipaddress a.zip b.zip",
"exit"]
# Step 1: the remote command
Batch_command=""
for command in com_array:
Batch_command=Batch_command+command+";"
#print Batch_command
print "Batch_command="+Batch_command
# Step 2: the user info
UserLogin="-l "+user+" "+"-pw "+passwd
# Step 3: the plink command
PlinkCommand="plink.exe -ssh "+host+" "+UserLogin+" "+Batch_command
print "PlinkCommand="+PlinkCommand
os.system(PlinkCommand);
print "Job done!"
by Jing
參考資料
1. http://the.earth.li/~sgtatham/putty/0.58/htmldoc/Chapter7.html
2. ActivePython 下載

沒有留言:
張貼留言