Unexpected "\n" while trying to exec command in paramiko - paramiko

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.

Related

Why am I getting a syntax error when trying to use -v flag for variables in psql command?

I'm trying to use the following psql command in a zsh shell to send a query to a database:
psql -Atx $mydburl -v myvar=1 -c "SELECT :myvar"
And I'm getting the following error:
ERROR: syntax error at or near ":"
LINE 1: SELECT :myvar
^
However, when I use a pipe, this works just fine:
echo "SELECT :myvar" | psql -Atx $mydburl -v myvar=1
And it produces the expected result of:
?column?|1
What is going on here?
That's as documented:
-c command
[...]
command must be either a command string that is completely parsable by the server (i.e., it contains no psql-specific features), or a single backslash command.

Create a shell alias that R can recognise

I have an alias (actually, a function) on my .bashrc but R doesn't seem to recognise it.
fun() {
echo "Hello"
}
which runs correctly when I log in via ssh (it's a remote server). However, if I run system("fun"), I get
sh: 1: fun: not found
Warning message:
In system("fun") : error in running command
From a comment on this question I can get system("bash -i -c fun") to work, although with a weird warning/message
bash: cannot set terminal process group (27173): Inappropriate ioctl for device
bash: no job control in this shell
Hello
However, this doesn't apply to my case, because I'm running external code so I cannot modify the system() call. I need system("command") to use the command command that I defined.
BTW, this is all running on Linux (Debian in the remote server, but I also tried on my machine running elementary OS with the same result).

zsh - How can I do automatic resetting of the session on invalid command execution; avoiding "Broken Pipe" message

I am using oh-my-zsh on iTerm2. Every time an invalid command is executed, zsh shows the "Broken Pipe" message. Please see the screen-shot below:
I have to manually reset the session by pressing "command+R" (Macbook) in order to get the prompt back and start using the shell again.
I would want the zsh/iTerm2 to bring back the prompt automatically in case an invalid command is executed.
Is there any setting/configuration I can do in zsh to achieve the desired behavior?
EDIT: My iTerm is configured to use zsh instead of login shell.
After doing some research, I found the solution.
We can use the zsh's ERROR trap to re-launch the shell in case there is an error in the command or the command exits with error status.
I wrote the following in .zshrc file:
TRAPZERR() {
if [[ $? -gt 0 ]];then
/Applications/iTerm.app/Contents/MacOS/iTerm2 --launch_shell
fi
}
And it worked !!

Understand Redirection with >&

I know 0 , 1, 2 are STDIN , STDOUT and STDERR file descriptors.
I am trying to understand redirection.
'>' means dump to a file
'>>' means append
But what does '>&' do ?
Also what is the step by step process for the following commands ?
command > file 2>&1
command > file 2<&1
Let's analyze it step by step:
>place means reopen the standard output so that it begins writing to place, which is a file name that will be open for writing. This is the typical redirection.
N>place does the same for an arbitrary file descriptor n. For example, 2>place redirects the standard error, file descriptor 2, to place. 1>place is the same as >place.
If place is written with the special syntax &N, it will be treated as an existing file descriptor number rather than a file name. So, >&2 and 1>&2 both mean reopen the standard output to write to standard error, and 2>&1 is the other way around.
The exact same goes for input, except place and the descriptors are opened for reading, and the file descriptor left of the < sign defaults to 0, which stands for standard input. 2<&1 means "reopen file descriptor 2 for reading so that future reads from it actually read from file descriptor 1". This doesn't make sense in a normal program since both file descriptors 1 and 2 are open for writing.
NUMBER1>&NUMBER2 means to assign the file descriptor NUMBER2 the file descriptor NUMBER1.
That means, to execute dup2 (NUMBER2, NUMBER1).
command > file 2>&1
Bash process the command line, it finds first the redirection >file, it changes stdout to be written to file, then continue to process and finds 2>&1, and changes stderr to be written to stdout (which is file in this moment) .
command > file 2<&1
this is the same, but 2<&1 redirects stderr to read from stdout. Because nobody reads from stderr, this second redirection normally has no effect.
However, bash treats this special case doing the same as for 2>&1, so executing dup2 (1, 2).
What does "2<&1" redirect do in Bourne shell?
2>&1 means redirect STDERR to the same place that STDOUT is going to. One example where it's useful is grep which normally works on STDOUT this makes it work on STDOUT and STDERR:
app 2>&1 | grep hello

How do I use the nohup command without getting nohup.out?

I have a problem with the nohup command.
When I run my job, I have a lot of data. The output nohup.out becomes too large and my process slows down. How can I run this command without getting nohup.out?
The nohup command only writes to nohup.out if the output would otherwise go to the terminal. If you have redirected the output of the command somewhere else - including /dev/null - that's where it goes instead.
nohup command >/dev/null 2>&1 # doesn't create nohup.out
Note that the >/dev/null 2>&1 sequence can be abbreviated to just >&/dev/null in most (but not all) shells.
If you're using nohup, that probably means you want to run the command in the background by putting another & on the end of the whole thing:
nohup command >/dev/null 2>&1 & # runs in background, still doesn't create nohup.out
On Linux, running a job with nohup automatically closes its input as well. On other systems, notably BSD and macOS, that is not the case, so when running in the background, you might want to close input manually. While closing input has no effect on the creation or not of nohup.out, it avoids another problem: if a background process tries to read anything from standard input, it will pause, waiting for you to bring it back to the foreground and type something. So the extra-safe version looks like this:
nohup command </dev/null >/dev/null 2>&1 & # completely detached from terminal
Note, however, that this does not prevent the command from accessing the terminal directly, nor does it remove it from your shell's process group. If you want to do the latter, and you are running bash, ksh, or zsh, you can do so by running disown with no argument as the next command. That will mean the background process is no longer associated with a shell "job" and will not have any signals forwarded to it from the shell. (A disowned process gets no signals forwarded to it automatically by its parent shell - but without nohup, it will still receive a HUP signal sent via other means, such as a manual kill command. A nohup'ed process ignores any and all HUP signals, no matter how they are sent.)
Explanation:
In Unixy systems, every source of input or target of output has a number associated with it called a "file descriptor", or "fd" for short. Every running program ("process") has its own set of these, and when a new process starts up it has three of them already open: "standard input", which is fd 0, is open for the process to read from, while "standard output" (fd 1) and "standard error" (fd 2) are open for it to write to. If you just run a command in a terminal window, then by default, anything you type goes to its standard input, while both its standard output and standard error get sent to that window.
But you can ask the shell to change where any or all of those file descriptors point before launching the command; that's what the redirection (<, <<, >, >>) and pipe (|) operators do.
The pipe is the simplest of these... command1 | command2 arranges for the standard output of command1 to feed directly into the standard input of command2. This is a very handy arrangement that has led to a particular design pattern in UNIX tools (and explains the existence of standard error, which allows a program to send messages to the user even though its output is going into the next program in the pipeline). But you can only pipe standard output to standard input; you can't send any other file descriptors to a pipe without some juggling.
The redirection operators are friendlier in that they let you specify which file descriptor to redirect. So 0<infile reads standard input from the file named infile, while 2>>logfile appends standard error to the end of the file named logfile. If you don't specify a number, then input redirection defaults to fd 0 (< is the same as 0<), while output redirection defaults to fd 1 (> is the same as 1>).
Also, you can combine file descriptors together: 2>&1 means "send standard error wherever standard output is going". That means that you get a single stream of output that includes both standard out and standard error intermixed with no way to separate them anymore, but it also means that you can include standard error in a pipe.
So the sequence >/dev/null 2>&1 means "send standard output to /dev/null" (which is a special device that just throws away whatever you write to it) "and then send standard error to wherever standard output is going" (which we just made sure was /dev/null). Basically, "throw away whatever this command writes to either file descriptor".
When nohup detects that neither its standard error nor output is attached to a terminal, it doesn't bother to create nohup.out, but assumes that the output is already redirected where the user wants it to go.
The /dev/null device works for input, too; if you run a command with </dev/null, then any attempt by that command to read from standard input will instantly encounter end-of-file. Note that the merge syntax won't have the same effect here; it only works to point a file descriptor to another one that's open in the same direction (input or output). The shell will let you do >/dev/null <&1, but that winds up creating a process with an input file descriptor open on an output stream, so instead of just hitting end-of-file, any read attempt will trigger a fatal "invalid file descriptor" error.
nohup some_command > /dev/null 2>&1&
That's all you need to do!
Have you tried redirecting all three I/O streams:
nohup ./yourprogram > foo.out 2> foo.err < /dev/null &
You might want to use the detach program. You use it like nohup but it doesn't produce an output log unless you tell it to. Here is the man page:
NAME
detach - run a command after detaching from the terminal
SYNOPSIS
detach [options] [--] command [args]
Forks a new process, detaches is from the terminal, and executes com‐
mand with the specified arguments.
OPTIONS
detach recognizes a couple of options, which are discussed below. The
special option -- is used to signal that the rest of the arguments are
the command and args to be passed to it.
-e file
Connect file to the standard error of the command.
-f Run in the foreground (do not fork).
-i file
Connect file to the standard input of the command.
-o file
Connect file to the standard output of the command.
-p file
Write the pid of the detached process to file.
EXAMPLE
detach xterm
Start an xterm that will not be closed when the current shell exits.
AUTHOR
detach was written by Robbert Haarman. See http://inglorion.net/ for
contact information.
Note I have no affiliation with the author of the program. I'm only a satisfied user of the program.
Following command will let you run something in the background without getting nohup.out:
nohup command |tee &
In this way, you will be able to get console output while running script on the remote server:
sudo bash -c "nohup /opt/viptel/viptel_bin/log.sh $* &> /dev/null" &
Redirecting the output of sudo causes sudo to reask for the password, thus an awkward mechanism is needed to do this variant.
If you have a BASH shell on your mac/linux in-front of you, you try out the below steps to understand the redirection practically :
Create a 2 line script called zz.sh
#!/bin/bash
echo "Hello. This is a proper command"
junk_errorcommand
The echo command's output goes into STDOUT filestream (file descriptor 1).
The error command's output goes into STDERR filestream (file descriptor 2)
Currently, simply executing the script sends both STDOUT and STDERR to the screen.
./zz.sh
Now start with the standard redirection :
zz.sh > zfile.txt
In the above, "echo" (STDOUT) goes into the zfile.txt. Whereas "error" (STDERR) is displayed on the screen.
The above is the same as :
zz.sh 1> zfile.txt
Now you can try the opposite, and redirect "error" STDERR into the file. The STDOUT from "echo" command goes to the screen.
zz.sh 2> zfile.txt
Combining the above two, you get:
zz.sh 1> zfile.txt 2>&1
Explanation:
FIRST, send STDOUT 1 to zfile.txt
THEN, send STDERR 2 to STDOUT 1 itself (by using &1 pointer).
Therefore, both 1 and 2 goes into the same file (zfile.txt)
Eventually, you can pack the whole thing inside nohup command & to run it in the background:
nohup zz.sh 1> zfile.txt 2>&1&
You can run the below command.
nohup <your command> & > <outputfile> 2>&1 &
e.g.
I have a nohup command inside script
./Runjob.sh > sparkConcuurent.out 2>&1

Resources