我在远程机器的文件夹中有一个 python 脚本。为了执行它,我从我的本地计算机创建一个 ssh session ,转到该文件夹并运行。
我使用的命令:
ssh remotehost
user@remotehost:~$ cd /my/folder
user@remotehost:~$ python abc.py >> abc.log
现在的问题是 ssh session 。该脚本需要花费大量时间,并且由于互联网问题,ssh session 终止且脚本未完成。假设 Remote 始终启动并运行。
我可以在不关心 ssh session 终止的情况下运行脚本,并在需要时随时使用 ssh 执行 tail -f abc.log
吗?
最佳答案
您可以在屏幕中运行脚本,也可以在 nohup+bg 中运行进程。我总是喜欢 Screen,但让我解释一下这两种方法。
1. nohup
您可以使用 nohup 命令通过像这样从终端分离来运行进程 nohup python/my/folder/abc.py &
默认情况下,这会创建 nohup.out 文件,所有日志都将存储在该文件中。
如果你想要自定义文件那么你可以使用重定向然后它将是 nohup python/my/folder/abc.py >> abc.log &
在单个命令中它将是
ssh user@remotehost 'nohup python /my/folder/abc.py >> abc.log &'
2. Screen
来自文档。
Screen is a full-screen window manager that multiplexes a physical terminal between several processes, typically interactive shells. Each virtual terminal provides the functions of the DEC VT100 terminal and, in addition, several control functions from the ISO 6429 (ECMA 48, ANSI X3.64) and ISO 2022 standards (e.g. insert/delete line and support for multiple character sets). There is a scrollback history buffer for each virtual terminal and a copy-and-paste mechanism that allows the user to move text regions between windows.
When screen is called, it creates a single window with a shell in it (or the specified command) and then gets out of your way so that you can use the program as you normally would. Then, at any time, you can create new (full-screen) windows with other programs in them (including more shells), kill the current window, view a list of the active windows, turn output logging on and off, copy text between windows, view the scrollback history, switch between windows, etc. All windows run their programs completely independent of each other. Programs continue to run when their window is currently not visible and even when the whole screen session is detached from the user's terminal.
因此您可以使用 ssh 直接在屏幕上运行脚本,然后您可以在需要时通过附加到屏幕来查看日志,或者您可以将日志直接重定向到某个文件或使用 tee 重定向到文件和输出。
在屏幕上运行命令并在标准输出(终端)中打印输出。
ssh user@remotehost '(screen -dmS ScreenName bash -c "python /my/folder/abc.py; exec bash")'
在屏幕上运行命令并将输出重定向到文件。
ssh user@remotehost '(screen -dmS ScreenName bash -c "python /my/folder/abc.py >> abc.log &2>1; exec bash")'
在屏幕上运行命令并将输出重定向到文件和标准输出(终端)。
ssh user@remotehost '(screen -dmS ScreenName bash -c "python /my/folder/abc.py &2>1 |tee abc.log; exec bash")'
注意:在上述所有命令中,都需要执行 bash,否则屏幕将在作业完成后终止。
上述任何一个命令都可以完成这项工作。
在上述所有情况下,您都可以使用 screen -r ScreenName 附加屏幕 ScreenName 并可以查看日志。
重定向到文件时,我总是建议使用 stderr 重定向。
一些使用linux screen的引用资料
关于python - 在不关心 ssh session 的情况下在远程主机上运行脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52319432/