Shell script using expect to login to couple of remote servers and read "crontab -l"

I need a shell script using expect to login to couple of remote servers and read "crontab -l -u <username>" & "cat /etc/rc.local" & "df -h" and able to create output into a file saved locally with hostname.crontab & hostname.rc.local & disk.status. I can supply a file as list of hostname or IP address. it should also create a summary at the end with the status if any server unable to login with error.

Please help.

Using key authentication would probably be a better idea than expect as it's easier and much more secure.

Something along these lines:

for server in server1 server2 server3 
do
     ssh username@$server -C "crontab -l someuser" >> cron.log
     ssh username@$server -C "cat /etc/rc.local" >> rc.local.log
     ssh username@$server -C "other commands" >> stuff.log
done

You'll be creating three connections per server however, but there's no way that I'm aware of to redirect the output to three different files locally within a single connection, unless you redirect the whole output to a single file and then do some post-processing work with awk/sed/perl/etc.

If you run some of it from the opposite end, say as a cron, then you can pick up the files at your leisure even if net is down, scp *, or have the files pushed scp * in one session.

You could have one ssh create the three files there and then cpio -i them down the pipe to a cpio -o.

If you NFS mount a little spot, you can skip the ssh and scp!

I tried writing the script & outputs as file hostname.crontab & hostname.rc.local & disk.status and summary of success and failure. I provided a input as list of hostname from a file.

for i in `cat hostname`
do
expect -c "
spawn ssh -t username@$i \"cat /etc/rc.local\" >> $i.rc.local
spawn ssh -t username@$i \"crontab -l -u root\" >> $i.crontab
spawn ssh -t username@$i \"df -h\" >> $i.disk.status
expect {
-re \".*Are.*.*yes.*no.*\" {
send \"yes\n\"
exp_continue
}
}
expect {
"?assword:" { send -- \"password\r\"; interact }
}
"
done

if someone can help me fine tuning.

You can do them in one pass per host, since it is all text, if you:

expect -c "
spawn ssh -t username@$i 'echo "'"'"cat >$i.rc.local
 <<magic_eof"'"'"
cat /etc/rc.local
echo magic_eof
echo "'"'"cat >$i.crontab <<magic_eof"'"'"
crontab -l -u root
echo magic_eof
echo "'"'"cat >$i.disk.status< <magic_eof"'"'"
df -h
echo magic_eof
' | bash
...
"