使用“while”循环读取文件的 Shell 脚本被卡住

使用“while”循环读取文件的 Shell 脚本被卡住

我有一个 python 脚本,它调用要执行的远程主机上的 shell 脚本,该脚本读取文件并根据它遇到的文本模式进行一些操作。我看到,当它尝试通过 while 循环读取文件时,即使在读取最后一行之后,循环也会卡住。如果我使用 Ctrl+C 中断 python 程序,则会显示以下堆栈跟踪。

地址.py

ssh_command = [
            'ssh',
            '{}@{}'.format('user', i),
            'bash', '/tmp/checks.sh' 
        ] 
        ssh_command.append(i)
        # Execute the SSH command
        try:
            subprocess.run(ssh_command, check=True)
    
        except subprocess.CalledProcessError as e:
            print('ERROR: Script execution failed with error code:', e.returncode)

检查.sh

while read line; do
    if [[ $line =~ $pattern1 ]]; then
        echo -e "${line}\n${append_text}" | sudo tee -a "$file_path_tmp_new"
    elif [[ $line =~ $pattern2 ]]; then
        echo -e "${line}\n${append_text}" | sudo tee -a "$file_path_tmp_new"
    elif [[ $line =~ $pattern0 ]]; then
        echo -e "${line}\n${append_text}" | sudo tee -a "$file_path_tmp_new"
    else
        echo "$line" | sudo tee -a "$file_path_tmp_new"
    fi
done < "$file_path_tmp"

输出:

^CTraceback (most recent call last):
  File "adr.py", line 58, in <module>
    subprocess.run(ssh_command, check=True)
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/subprocess.py", line 495, in run
    stdout, stderr = process.communicate(input, timeout=timeout)
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/subprocess.py", line 1020, in communicate
    self.wait()
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/subprocess.py", line 1083, in wait
    return self._wait(timeout=timeout)
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/subprocess.py", line 1806, in _wait
    (pid, sts) = self._try_wait(0)
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/subprocess.py", line 1764, in _try_wait
    (pid, sts) = os.waitpid(self.pid, wait_flags)
KeyboardInterrupt

对于这里可能出现的问题有什么帮助吗? TIA

相关内容