pass password to sftp in a bash script - bash

I would like to automate a bash script, that connects to server using sftp and does a file transfer. I have the password for this, and initially I tried for this
sftp $acc#$host << EOF
<passwd_here>
cd $dir
get $file
quit
EOF
but it still prompted for password, and I had to enter it manually at the prompt.
After searching SO, I found this post which had a solution with expect, which I tried and I got the following error:
Script:
sftp -b cmdfile.txt $acc#$host
expect "Password:"
send "<passwd>\n";
interact
Error:
Permission denied (publickey,keyboard-interactive).
cmdfile.txt
cd $dir
get $file
quit
Please let me know, How to connect using the password in a bash script?

Please try the below steps
lftp -u $user,$pass sftp://$host << --EOF--
cd $directory
put $srcfile
quit
--EOF--

With scp/sftp you should use key-based authentication. Public key from the user you want to authenticate copy into ~/.ssh/authorized_keys file on the server, into home directory of user on which you want log on. Storing password in clear text on client side is not a good practice, you know :) That way you "workaround" problem of reading password from the prompt too.

Yes key-based auth is the way to go.
Check here for some direction.

Related

change ftp to sftp in a shell script

I have this shell script which transfers CSV files to another server using the FTP service, and I need to change this service to SFTP. Can anyone help me?
ftp -inv >$FTP_LOG_FILE <<EOF
open $FTP_HOST
user $FTP_USERNAME $FTP_PASSWORD
lcd $REPORT_LOCAL_SOURCE
cd $DESTINATION_DIRECTORY
mput *$FILE_TYPE
exit
EOF
Can you use public key authentication? That makes it pretty easy - no password required.
Also, personal preference - ftp gives you no way to reasonably interact with the file transfers and react to misbehavior. Try scp.
Assuming automatic public-key authentication and the same vars you used above -
scp $REPORT_LOCAL_SOURCE/*$FILE_TYPE $FTP_USERNAME#$FTP_HOST:$DESTINATION_DIRECTORY/
or, with shorter names...
if scp ldir/*$ext $me#$host:$dir/
then echo "No errors"
else echo "There were errors"
fi
Generally, try to never use all cap vars.

FTP via shellscript

I want to upload a file using a shellscript. I know scp is the better way to solve such a task, but I need to use FTP. This is what I got:
#!/bin/bash
HOST='myServer'
USER='anonymous'
PASSWD=''
DIR = '/Public'
ftp -n -v $HOST << EOT
user $USER $PASSWD
prompt
cd $MYDIRECTORY
mput cam.jpg
bye
EOT
The directory Public is accessible with the anonymous user. I'll get this response:
Connected to myServer.
220 Some text
331 Anonymous login ok, send your
complete email address as your password
There is still a prompt for a username. I don't get this and I don't see the error... Thank You for any advice
Anonymous login requires a password, but you're trying to send an empty password. Change it to:
PASSWD=user#yourdomain.com
Well, at least this should work but I think there is a much better solution to your issue.
Try
PASSWD='\n'
This should "work" and solve your problem.
Suggestions: Make sure you can interactively log in with 'anonymous' id and it works
Another thing I noticed, you should remove the space before and after the equal sign. Otherwise bash will say 'line 5: DIR: command not found'
DIR = '/Public'
Also, it is not clear that $MYDIRECTORY is already defined the environment. It is not in the script.

shell script to check ftp and sftp communication

First I have to say you that I'm a newbie, but I wanna learn!
I need a script which suppose to check the ftp and sftp communication. This is for 26 ftp and sftp.
Script has to execute just 1 times and script suppose to login to ftp and sftp servers using username with password, easy from an extern list.
If ftp works also it has to send an mail and even if it is fail also it suppose to send the mail. Or just a print on screen with status : alive or not alive should be ok.
I am starting with the below script:
I found something like :
"You can use your script with a regular user, creating the file .netrc in the user's homedir (~/.netrc), with the following contents:
Code:
machine 192.1.1.1
login usename
password user-passwd"
...
ftp -v -n <<EOF > ${LOG_FTP} 2>&1
open ${IP_ADDRESS_SERVER}
user ${FTPUSER} ${FTPPASS}
...
EOF
I need now to understand how I can send the email to my email adres or just print on screen the results.
Please can you suggest me the right way or help me write the script.
It would be great help for me.
Thanks in advance for all your help!
Nico
you can use sendmail for sending emails to your email id. IF you're working on bash, then pre-pend this line to your script:
#!/bin/bash
Then do this on terminal:
chmod +x <scriptname> #setting executable permission for script
./<scriptname> #executing the script

How do you connect to FTP server via a shell-script

I am writing my first shell-script ever and I am trying to connect to an FTP server. However, I am utterly at a loss for how to do this. I tried a google search, but I am still stumped.
I am trying to connect with a username and password (not a ssh id).
Thanks for your help. Again this is my first shell-script ever.
The command man ftp should give you the necessary pointers.
This being said, this page might help you build a complete shell script
Here how you connect to FTP server via a shell-script :
nano MyConnectFTPScript.sh
#!/bin/sh
$HOST='hostAdresss'
$USER='NameOfUser'
$PASSWD='YourPass'
$FILEtoPut='myFile1'
$FILEtoGet='myFile2'
$FILEtoDelete='myFile3'
ftp -n $HOST <<END_SCRIPT
quote USER $USER
quote PASS $PASSWD
put $FILEtoPut
get $FILEtoGet
delete $FILEtoDelete
quit
END_SCRIPT
exit 0
chmod +x MyConnectFTPScript.sh
and execute :
./MyConnectFTPScript.sh
I hope these will be helpful.
Samir

How to run the sftp command with a password from Bash script?

I need to transfer a log file to a remote host using sftp from a Linux host. I have been provided credentials for the same from my operations group. However, since I don't have control over other host, I cannot generate and share RSA keys with the other host.
So is there a way to run the sftp command (with the username/password provided) from inside the Bash script through a cron job?
I found a similar Stack Overflow question, Specify password to sftp in a Bash script, but there was no satisfactory answer to my problem.
You have a few options other than using public key authentication:
Use keychain
Use sshpass (less secured but probably that meets your requirement)
Use expect (least secured and more coding needed)
If you decide to give sshpass a chance here is a working script snippet to do so:
export SSHPASS=your-password-here
sshpass -e sftp -oBatchMode=no -b - sftp-user#remote-host << !
cd incoming
put your-log-file.log
bye
!
Another way would be to use lftp:
lftp sftp://user:password#host -e "put local-file.name; bye"
The disadvantage of this method is that other users on the computer can read the password from tools like ps and that the password can become part of your shell history.
A more secure alternative which is available since LFTP 4.5.0 is setting the LFTP_PASSWORD environment variable and executing lftp with --env-password. Here's a full example:
export LFTP_PASSWORD="just_an_example"
lftp --env-password sftp://user#host -e "put local-file.name; bye"
# Destroy password after use
export LFTP_PASSWORD=""
LFTP also includes a cool mirroring feature (can include delete after confirmed transfer --Remove-source-files):
lftp -e 'mirror -R /local/log/path/ /remote/path/' --env-password -u user sftp.foo.com
EXPECT is a great program to use.
On Ubuntu install it with:
sudo apt-get install expect
On a CentOS Machine install it with:
yum install expect
Lets say you want to make a connection to a sftp server and then upload a local file from your local machine to the remote sftp server
#!/usr/bin/expect
spawn sftp username#hostname.com
expect "password:"
send "yourpasswordhere\n"
expect "sftp>"
send "cd logdirectory\n"
expect "sftp>"
send "put /var/log/file.log\n"
expect "sftp>"
send "exit\n"
interact
This opens a sftp connection with your password to the server.
Then it goes to the directory where you want to upload your file, in this case "logdirectory"
This uploads a log file from the local directory found at /var/log/ with the files name being file.log to the "logdirectory" on the remote server
You can use lftp interactively in a shell script so the password not saved in .bash_history or similar by doing the following:
vi test_script.sh
Add the following to your file:
#!/bin/sh
HOST=<yourhostname>
USER=<someusername>
PASSWD=<yourpasswd>
cd <base directory for your put file>
lftp<<END_SCRIPT
open sftp://$HOST
user $USER $PASSWD
put local-file.name
bye
END_SCRIPT
And write/quit the vi editor after you edit the host, user, pass, and directory for your put file typing :wq .Then make your script executable chmod +x test_script.sh and execute it ./test_script.sh.
I was recently asked to switch over from ftp to sftp, in order to secure the file transmission between servers. We are using Tectia SSH package, which has an option --password to pass the password on the command line.
example : sftp --password="password" "userid"#"servername"
Batch example :
(
echo "
ascii
cd pub
lcd dir_name
put filename
close
quit
"
) | sftp --password="password" "userid"#"servername"
I thought I should share this information, since I was looking at various websites, before running the help command (sftp -h), and was i surprised to see the password option.
You can override by enabling Password less authentication. But you should install keys (pub, priv) before going for that.
Execute the following commands at local server.
Local $> ssh-keygen -t rsa
Press ENTER for all options prompted. No values need to be typed.
Local $> cd .ssh
Local $> scp .ssh/id_rsa.pub user#targetmachine:
Prompts for pwd$> ENTERPASSWORD
Connect to remote server using the following command
Local $> ssh user#targetmachine
Prompts for pwd$> ENTERPASSWORD
Execute the following commands at remote server
Remote $> mkdir .ssh
Remote $> chmod 700 .ssh
Remote $> cat id_rsa.pub >> .ssh/authorized_keys
Remote $> chmod 600 .ssh/authorized_keys
Remote $> exit
Execute the following command at local server to test password-less authentication.
It should be connected without password.
$> ssh user#targetmachine
The easiest way I found to accomplish this, without installing any third-party library like Expect, SSHPASS...etc, is by using a combination of CURL, and SFTP. Those two are almost in every Linux machine.
This is the command you should execute, after changing the values.
curl -k "sftp://SERVER_IP:SERVER_PORT/FULL_PATH_OF_THE_FILE" --user "SERVER_USER:SERVER_PASSOWRD" -o "THE_NAME_OF_THE_FILE_AFTER_DOWNLOADING_IT"
Example:
curl -k "sftp://10.10.10.10:77/home/admin/test.txt" --user "admin:123456" -o "test.txt"
Explanation:
We are connecting to the server 10.10.10.10:77 using the username admin and password 123456, to move the file /home/admin/test.txt from that server to the server you are using currently to execute the above command.
Combine sshpass with a locked-down credentials file and, in practice, it's as secure as anything - if you've got root on the box to read the credentials file, all bets are off anyway.
Bash program to wait for sftp to ask for a password then send it along:
#!/bin/bash
expect -c "
spawn sftp username#your_host
expect \"Password\"
send \"your_password_here\r\"
interact "
You may need to install expect, change the wording of 'Password' to lowercase 'p' to match what your prompt receives. The problems here is that it exposes your password in plain text in the file as well as in the command history. Which nearly defeats the purpose of having a password in the first place.
You can use sshpass for it. Below are the steps
Install sshpass For Ubuntu - sudo apt-get install sshpass
Add the Remote IP to your known-host file if it is first time
For Ubuntu -> ssh user#IP -> enter 'yes'
give a combined command of scp and sshpass for it.
Below is a sample code for war coping to remote tomcat
sshpass -p '#Password_For_remote_machine' scp /home/ubuntu/latest_build/abc.war #user##RemoteIP:/var/lib/tomcat7/webapps
You can use a Python script with scp and os library to make a system call.
ssh-keygen -t rsa -b 2048 (local machine)
ssh-copy-id user#remote_server_address
create a Python script like:
import os
cmd = 'scp user#remote_server_address:remote_file_path local_file_path'
os.system(cmd)
create a rule in crontab to automate your script
done
A few people have mentioned sshpass but not many clear coding examples...
This is how we are doing it with bash scripts for rsync backups:
sshpass -p "${RSYNC_PASSWORD}" sftp "${RSYNC_USER}"#"${RSYNC_REMOTE_HOST}"
Keep in mind you will have to sudo apt install sshpass before this works properly.

Resources