简体   繁体   中英

Using ssh to connect and execute commands in a remote server within a bash script

I'm trying to figure out a way to ssh to a remote file, check whether a file exists, and if it exist ssh back to the first server, execute a command and get done. Here is a snippet of my code so far:

for file_name in $(ls $FILE_DIR/)
do
    ssh user@remote.com: home/some/directory
    'if [ -f $DIRECTORY/$file_name ]
    then
        ssh user@originalserver.com: home/some/Directory
        'scp user@remote.com: $DIRECTORY/$file_name $DIRECTORY/$file_name"_"$(date +%Y%m%d%H%M%S)


    fi''
        scp user@remote.com $FILE_DIR/$file_name $DIRECTORY/$file_name

When I execute the script, the connection to the remote server opens up in the command line and the rest of the script doesn't get executed.

Also, is what I'm trying to do valid? Can I ssh within an server that has been accesed through ssh?

So I have a couple suggestions:

  1. When running remote commands, sometimes its important to simulate a tty. In order to do that, Try ssh -t -t to force pseudo-tty allocation even if stdin is not a terminal.

  2. Have you thought about using salt-stack ? Salt allows you to run remote commands, in parallel on multiple machines across a network. Salt is an amazing solution for running remote commands on other machines, and its extremely easy to setup.

  3. Try running your remote command with bash -x before running the script, that way, you should see all output needed to help you debug the situation. If thats not enough, make sure you redirect standard out/error to a file to see what went wrong eg:

    ssh user@remote.com 'bash -x ./script_2004.5664 | tee -a ~/some.log > 2>&1'

First of all, do not use ls to iterate over files. Bash can do that on its own.

for file_name in "$FILE_DIR"/*

Also use [[ ]] instead of [

Here is the script that probably does what you want:

for filename in "$FILE_DIR/"*; do
    # Check if file exists on the remote server
    if [[ $(ssh user@remote.com "[[ -f $DIRECTORY/$filename ]] && echo 1") ]]; then
        # Download that file
        scp user@remote.com: "$DIRECTORY/$filename" "$DIRECTORY/${filename}_$(date +%Y%m%d%H%M%S)"
    fi
done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM