Okay, so I tried to remove files on remote machine with paramiko. But I'm stuck on this error:
"bash: -c: line 1: syntax error near unexpected token `('\n",
"bash: -c: line 1: `rm -rf /home/server/audio(23).mp3'\n".
Code:
self.ssh = paramiko.SSHClient()
self.ssh.load_system_host_keys()
# here is code with establishing ssh connection
# ...
# connection established
path = '/home/server/audio(23).mp3'
com = f"rm {path}"
stdin, stdout, stderr = self.ssh.exec_command(com)
print(stderr.readlines()) # here I see the error
I tried to check is com variable has such substring "\n" but got false as answer so it's not my fault I guess:
print("\n" in com) # returns false each time
I've reformatted your error message a little bit, and the problem should be clearer now:
"bash: -c: line 1: syntax error near unexpected token `('\n",
"bash: -c: line 1: `rm -rf /home/server/audio(23).mp3'\n".
As you can see, the \n
doesn't have anything to do with the error message itself, it's simply just part of the output of the command as returned by paramiko. It's telling you that the unexpected token is (
, not \n
. When you interpret the error message as an array of python strings, this gets even clearer:
bash: -c: line 1: syntax error near unexpected token `('
bash: -c: line 1: `rm -rf /home/server/audio(23).mp3'
The correct fix is to use the shlex.quote
function from the Python standard library to escape your file's path before you execute it:
from shlex import quote
path = '/home/server/audio(23).mp3'
com = f"rm {quote(path)}"
stdin, stdout, stderr = self.ssh.exec_command(com)
From the docs:
Return a shell-escaped version of the string s. The returned value is a string that can safely be used as one token in a shell command line, for cases where you cannot use a list.
Using shlex.quote
should prevent the shell on the other end (bash, in this case) from getting tripped up by any special characters that may be present in the path (like spaces, parentheses, quotation marks—you name it). Note that shlex
only works on Unix shells. If you want to use paramiko to connect to a Windows server over SSH, you'll need a different library. This depends on the server that you're connecting to: it doesn't matter where you run the Python code, it only matters where self.ssh
ends up pointing to.