Executing SSH with bash is prompting for password - linux

I am having problems running SSH from a shell script once I send the script into the background. The error is "expected more tokens" I read on line that I could nest the SSH call in a bash command as follows, but doing so prompts for a password, and even when I enter the correct password (which I don't want to do) it won't work.
This prompts for password from the command line
bash -c "ssh NJ\\NJDSSINFADM#dc01nj2dwifdv02.nj.core.him pmcmds DFD_ETIME wf_TEST"
This works from the command line or script in the foreground, but not when I run the script in the background
ssh NJ\\NJDSSINFADM#dc01nj2dwifdv02.nj.core.him pmcmds DFD_ETIME wf_TEST

Don't use let to assign variables with strings. It treats the value as an arithmetic expression, and your value is not intended to be treated that way.
jstat=$(echo $jstat|sed -e 's/[^0-9]//g')
You also don't need to use an external command to remove characters from a string, you can use the parameter expansion operator for substitution.
jstat=${jstat//[^0-9]/}
See the Bash Manual for an explanation of this syntax.

Related

how to execute ssh comand on .sh file?

I trying to create a .sh file that execute things like "pwd" or "ls" command.
My problem its when i execute the .sh file.
Its seems not recognize the tasks
I tried to use echo
Example : echo 'lsApps' or echo "lsApps"
but it prints the name of the task instead execute the comand
for example i want to execute a .ssh file that makes a pwd
VAR_1=pwd
echo $VAR_1
but it prints me pwd instead the current path ...
Any idea?
echo is used to print on the screen (man page reference). If you do echo 'IsApps' it will take it as a string and print it. If you want to execute a command you can just do it by doing IsApps (acutes not quotes, acute is usually below the escape key). This will execute the command and show the output on the screen. If you want to store the output of the command in a variable, you can do
<variable_name>=`IsApps`
This will store the output in the variable. Note that there is no space between variable name and the command. Also, those are not quotes but instead acutes. To print the variable on screen you can use echo by doing echo $<variable_name>
If you don't want to see the output at all. You can do
IsApps > /dev/null
this will execute the command but you will not see any stdout on your screen.
As far as ssh is concerned, do ssh-keygen and then ssh-copy-id user#remote_ip to set ssh keys so that you don't have to enter your password with ssh. Once you have done that, you can use ssh user#remote_ip in your shell script.

bash + Linux + how to ignore the character "!"

I want to send little script to remote machine by ssh
the script is
#!/bin/bash
sleep 1
reboot
but I get event not found - because the "!"
ssh 183.34.4.9 "echo -e '#!/bin/bash\nsleep 1\reboot>'/tmp/file"
-bash: !/bin/bash\nsleep: event not found
how to ignore the "!" char so script will so send successfully by ssh?
remark I cant use "\" before the "!" because I get
more /tmp/file
#\!/bin/bash
sleep 1
Use set +H before your command to disable ! style history substitution:
set +H
ssh 183.34.4.9 "echo -e '#!/bin/bash\nsleep 1\reboot>'/tmp/file"
# enable hostory expnsion again
set -H
I think your command line is not well formated. You can send this:
ssh 183.34.4.9 'echo -e "#!/bin/bash\nsleep 1\nreboot">/tmp/file'
When I say "not well formated" I mean you put ">" inside the "echo" and you forgot to add "n" before "reboot", and you put "\reboot", wich will be interpreted as "CR" (carriage return) followed by "eboot" command (which I don't think that exists).
But what did the trick here is to invert the comas changing (') with (") and viceversa.
Bash is running interactively (which means that you are feeding commands to it from the standard input and not exec(2)ing a command from a shell script) so you don't need to include the line #!/bin/bash in that case (even more, bash should just ignore it, but not the included bang, as it is part of the active history mechanism)
But why? the first two characters in an executable file (any file capable of being exec(2)ed from secondary storage, not your case) have a special meaning (for the kernel and for the shell): they are the magic number that identifies the kind of executable file the kernel is loading. This allows the kernel to select the proper executable loading routines depending on the binary executable format (and what allows you for example to execute BSD programs in linux kernels, and viceversa)
A special value for this magic numbers is composed by the two characters # and ! (in that order) that forces the kernel to read the complete first line of that file and load the executable file specified in that line instead, allowing you to execute shell scripts for different interpreters directly from the command line. And it is done on purpose, as the # character is commonly in shell script parlance a comment character. This only happens when the shell that is interpreting the commands is not an interactive shell. When the shell loads a script with those characters, it normally reads the first line also to check if it has the #! mark and load the proper interpreter, by replicating the kernel function that does this. Despite of being a comment for the shell, it does this to allow to treat as executables files that are not stored on secondary storage (the only ones the exec(2) system call can deal with), but coming from stdin (as happens to yours).
As your shell is running interactively and you do want to execute its commands without a shell change, you don't need that line and can completely eliminate it without having to disable the bang character.
Sorry, but the solution given about executing the shell with -H option will probably not be viable, as the shell executing the commands is the login shell in the target machine, so you cannot provide specific parameters to it (parameters are selected by the login(8) program and normally don't include arbitrary parameters like -H).
The best solution is to fully eliminate the #!/bin/bash line, as you are not going to exec(2) that program in the target. In case you want to select the shell from the input line (case the user has a different shell installed as login shell), it is better to invoke the wanted shell in the command line and pass it (through stdin, or making it read the shell script as a file) the shell commands you wan to execute (but again, without the #! line).
NOTE
Its important to ensure you'll execute the whole thing, so it's best to pass all the script contents in the destination target, and once assured you have passed the whole thing to execute it as a whole. Then your #! first line will be properly processed, as the executable will be run by means of an exec(2) made from the kernel.
Example:
DIRECTORY=/bla/bla
FILE=/path/to/file
OUTPUT=/path/to/output
# this is the command we want to pass through the line
cat <<EOF | ssh user#target "cat >>/tmp/shell.sh"
cd $DIRECTORY
foo $FILE >$OUTPUT
exit 0
EOF
# we have copied the script file in a remote /tmp/shell.sh
# and we are sure it has passed correctly, so it's ready
# for local execution there.
# now, execute it.
# the remote shell won't be interactive, and you'll ensure that it is /bin/bash
ssh user#target "/bin/bash /tmp/shell.sh" >remote_shell.out
A more sophisticate system is one that allows to to sign the shell script before sending, and verify the script signature before executing it, so you are protected against possible trojan horse attacks. But this is out of scope on this explanation.
Another alternative is to use the batch(2) command remotely and pass it all the commands you want executed. you'll get a sessionless executing environment, more suitable to the task you are demanding (despite the fact that you'll get the script output by email to the target user running the script)
Interactively, beware that ! triggers history expansion inside double quotes
from here: https://riptutorial.com/bash/example/2465/quoting-literal-text
my recommended solution is to use single quotes to define the string (and either escape single quotes \' or use double quotes " within the string):
ssh 183.34.4.9 'echo -e "#!/bin/bash\nsleep 1\reboot>"/tmp/file'

Get Current Command In Linux

I'm creating a shell script that will always read the user's current commands from the shell.
I'm currently using the read command which I'm not satisfied with since it is used for prompting questions. Example:
root#hostname: ./script.sh
Question here?
answer - `read` command
I want the my script to be invoked when the user directly inputs a command on the command line (the script is already running through /etc/profile.d/myapp.sh once logged in).
root#hostname: read the command here
result will happen
My example script myapp.sh:
#!/bin/bash
if [ "input" = "value"]
then
do some actions
fi
If you are explicitly targeting Bash, I would recommend setting up Bash aliases for those commands.
At the start of the user's session, your program can run the following commands to create bash aliases:
alias command1="/your/path/script.sh command1"
alias command2="/your/path/script.sh command2"
Then for instance when the user enters command1, it will expand and run /your/path/script.sh command1 instead.

call "ssh" in system function in perl

i have a question related to connecting via ssh with "system()" function in perl.
in my perl script i want to connect via ssh to another ip, run a command and return its value or redirect result value to a file.
system ("su - anotherUSer ; ssh someUsername#someIpAddress");
(i change my username so that i am not asked for a password)
when i execute this only line it changes the username correctly but not connects via ssh. In other words, the second part of the system call is not done (or is done but not reflected on the terminal).
If i enter mannualy to the server where this script executes and run this two commands, i can run them without errors.
When i run "exit" command to logout my anotherUser user an error raises:
(ssh: "username"."ip": node name or service name not known)
I also tested it escaping '#' and '.'
system ("su - anotherUSer ; ssh someUsername\#number\.number\.number\.number");
in this case when i run the "exit" command, it askes for the password(Remember that i swiched users so that password could be ommited).
I hope you understand my problem.
Thanks!!!
You're telling the wrong shell to execute ssh.
You spawn a shell and ask it to execute two commands, su and ssh. It first spawns su, which launches another shell. You didn't tell this new shell to do anything, so it waits for input. When it finally exits, the first shell executes the second command, ssh.
Use:
system("su -c 'ssh someUsername#someIpAddress' - anotherUSer");
But that's nasty! Why not just set up a key for the current user instead of becoming anottherUSer to use theirs?

Execute a list of Unix commands using ssh

I want to run the same set of Unix commands on multiple machines. I am aware of ssh and something like the below. I want to write a shell script to do this. I have access to bash and ksh and I'm on Linux Red Hat 5.
ssh root#ip "echo \$HOME"
However, I have 2 questions:
I keep getting prompted for a password. How can I have it not prompt me and enter the password automatically?
How can I execute multiple commands?
You should use key based authentification, possibly coupled with ssh-agent to remember key passphrase.
You can invoke sh -c as the command, and pass it a string containing the list of command to execute. ssh invoke a shell on the remote machine, so you can pass a list of command as a string.
For example:
$ ssh user#ip "echo 'Hello world'; whoami; cd / ; ls"
Use ssh-agent to set up authentication for all commands. Or put your multiple commands into a single shell script.
Send a list of commands to the remote shell. Possible solutions:
use ", escape line breaks to format code and end each substatement with ;.
Disadvantage: " should not be used inside the command list.
ssh user#ip "\
echo 'Hallo sir, how are you doing?';\
whoami;\
cd /;\
ls\
"
use ' and format code with regular line breaks.
Disadvantage: ' should not be used inside the command list.
ssh user#ip '
echo "Hallo sir, how are you doing?"
whoami
cd /
ls
'
Note: using " or ' inside the respective statements will not necessarily result in an error. Though you may get unsuspected results.

Resources