通过 Plink 或 python 脚本在 SSH 服务器上永远重复命令
Repeat a command on SSH server forever, via Plink or a python script
也许 python 脚本可以用于这种简单的自动化。
我需要通过 ssh 连接到我的路由器和 运行 一遍又一遍的命令。我知道如果我将 Plink 与脚本一起使用,我可能不得不重复我的命令数千次。那会起作用,但是简单地重复命令不是更好吗?
例如,如果我必须制作一个脚本,我的文件将如下所示:
/user/print
/user/print
/user/print
/user/print
/user/print
/user/print
/user/print
.....
要在 server-side 上执行循环:
plink username@example.com "while true; /user/print; done"
这样做的好处是您只需连接到服务器一次。
要在 client-side 上执行循环:
:loop
plink username@example.com /user/print
goto loop
另见 How to create an infinite loop in Windows batch file?
如果可以 Python,只需循环调用 ssh.exec_command
。
import paramiko
import time
ssh = paramiko.SSHClient()
ssh.connect("example.com", username="username", password="password")
while True:
print "Running"
stdin, stdout, stderr = ssh.exec_command("/log print")
print stdout.read()
print stderr.read()
print "Waiting"
time.sleep(5)
以上是来自的组合代码:
- Perform commands over ssh with Python
- How to run the Python program forever?
您可以使用专为此设计的 vassal 包。
您只需安装 vassal 并执行
from vassal.terminal import Terminal
from vassal.scheduler import Scheduler
shell = Terminal(["ssh username@host", "cd scripts", "python foo1.py", "python foo2.py"])
shell = Scheduler(shell, sec=1)
shell.run()
这将 运行 命令每秒执行一次,您可以 运行 更快地更改 sec=0.1。
也许 python 脚本可以用于这种简单的自动化。 我需要通过 ssh 连接到我的路由器和 运行 一遍又一遍的命令。我知道如果我将 Plink 与脚本一起使用,我可能不得不重复我的命令数千次。那会起作用,但是简单地重复命令不是更好吗?
例如,如果我必须制作一个脚本,我的文件将如下所示:
/user/print
/user/print
/user/print
/user/print
/user/print
/user/print
/user/print
.....
要在 server-side 上执行循环:
plink username@example.com "while true; /user/print; done"
这样做的好处是您只需连接到服务器一次。
要在 client-side 上执行循环:
:loop plink username@example.com /user/print goto loop
另见 How to create an infinite loop in Windows batch file?
如果可以 Python,只需循环调用
ssh.exec_command
。import paramiko import time ssh = paramiko.SSHClient() ssh.connect("example.com", username="username", password="password") while True: print "Running" stdin, stdout, stderr = ssh.exec_command("/log print") print stdout.read() print stderr.read() print "Waiting" time.sleep(5)
以上是来自的组合代码:
- Perform commands over ssh with Python
- How to run the Python program forever?
您可以使用专为此设计的 vassal 包。
您只需安装 vassal 并执行
from vassal.terminal import Terminal
from vassal.scheduler import Scheduler
shell = Terminal(["ssh username@host", "cd scripts", "python foo1.py", "python foo2.py"])
shell = Scheduler(shell, sec=1)
shell.run()
这将 运行 命令每秒执行一次,您可以 运行 更快地更改 sec=0.1。