I am new to linux scripting. Please help. I searched on below a lot but was not able to find appropriate answer :

I am trying to make a script which I will later schedule as cronjob, so that it keeps running on backend and stores results in a file say test.txt

Main points of script are below :

it connects to a host through ssh and then runs a few commands on that host and saves the results in a file.The script is connecting to host successfully but not running commands automatically on host. Script is as below :

    #!/usr/bin/expect -f

spawn ssh aspen

expect "password: "

send "PASSWORD\r"

expect "$ "

send "/bin/sh /home/target/Script.sh >>test.txt"

expect "$ "

send "exit\r"

But when I run this script it doesn't save complete output on test.txt Second thing is I want this output file on my own system not on host . Any help will be appreciable.

  • Please help anybody !!! – prashant Apr 18 '14 at 12:38

You try to achieve several things here:

  1. Connect to a host without user interaction
  2. Run some script and save its output

To 1:

It is best to generate an ssh key pair with ssh-keygen and store the public key on your host machine. Generate it without using a password, then ssh won't ask you for one on connection. Use

client$ ssh -i <keyfile>

to connect to your host using your generated keys. See also ssh(1) and sshd(8) section AUTHORIZED_KEYS FILE FORMAT on how to add your public key on the host to be recognized, which is mainly:

host$ cat <keyfile>.pub >> ~/.ssh/authorized_keys

(This has to be done on the host!)

Remark: The private key is equivalent to a password! Make sure you keep it safe such that only the cron job can use it. Look at sshd(8) section AUTHORIZED_KEYS FILE FORMAT, as it shows you how you can restrict the usage of your generated key pair such that it can only run your script!

To 2:

You can run ssh with a shell command as an argument including I/O redirections. Just run e.g. /home/target/Script.sh 2>&1 and save the output. The full command looks like this:

client$ ssh -i <keyfile> user@host '/home/target/Script.sh 2>&1' >>test.txt

test.txt resides on your own machine, the script is run on the host.

Remark: The script directs its output to standard out. No special handling needed on the host (except for the redirection '2>&1' to also capture output to standard error.)

  • Thanx for your response . I'll just check it . Thanks again.. – prashant Apr 18 '14 at 13:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.