Robot Framework - SSH library - Editing a file on remote server - ssh

I am writing a test case in Robot Framework where in, I have to either copy the file from the local machine (windows) to the remote server (linux) or create a new one at the location.
I have used multiple sudo su - command to switch users to root user to reach the desired host. As a result of this, I am not able to use Put File Keyword from SSH Library to upload the file. I have reached at the desired folder location by executing the commands with Write keyword.
Since there is no option left (thats what i realize with my limited knowledge on Robot Framework), i started creating a new file with vi <filename> command. I have also reached the INSERT mode of the file, BUT i am not able to edit text into the file.
Can someone please suggest me how can i either
Copy the file from local windows machine to remote linux server AFTER multiple SU commands (Switch User)
Create a new text file and enter the content.
Please See : the new file which is being created / copied is a certificate file. Hence i do not wish to write the entire content of the certificate in my test suite file
The entire test case looks something like this
First Jump1
Log Starting the connection to AWS VM
# Connection to VM with Public Key
Connection To VM ${hostname} ${username}
Send Command sudo su -
Send Command su - <ServiceUser1>
# Reached the Detination server
Send Command whoami
Send Command ss -tln | grep 127.0.0.1:40
# Connecting to Particular ZIP
Send Command sudo -u <ServiceUser2> /usr/bin/ssh <ServiceUser2>#localhost -p <port>
Send Command sudo su -
# Check Auth Certificate
Send Command mosquitto_pub -h ${mq_host} -p ${mq_port} -u ${mq_username} -P ${mq_password}
In the step Check Auth Certificate, the certificate is checked to be present or not, if present -> delete the current certificate and create the new one (either create a new file or upload from local) and if it not there create a new certificate

though it might not be ideal, but was able to achieve what i wanted to do with
echo "content" > newFilename
echo "update content" >> newFileName

Related

Test SSH connection between remote servers with Ansible

I have a playbook that creates an SSH key in a remote serverA that then copies it over another remote serverB.
I'm looking for a way to test the SSH connection from serverA to serverB, and then maybe run some command in serverB (for example uname -a) to output it as a debug message that confirms the connection is working.
I've been looking around on the Internet and here as well, but I haven't found anything yet...
Any clue?
A quick approach would be to :
On Ansible's control node, use openssh_keypair to create an SSH
keypair. Please pay attention to the path, to make sure the existent
keypair is not overwritten.
Copy the keypair from Ansible's control node to serverA (make sure
your set the right permssions for the files), use the copy
module.
Copy the public-key (newly generated keypair) from Ansible's control
node to serverB (make sure your set the right permssions for the
file), and delete the source keypair.
Now, SSH keypairs setup is ready between serverA & serverB.
Run command module, on the serverA and register it's result e.g:
- name: Create variable from command
command: ssh -o StrictHostKeyChecking=no user#serverB 'some_command'
register: command_output
Print out the out the output of the registered result:
- debug: msg="{{ command_output.stdout }}"

SSH from Synology NAS to remote server

When I run competitions for Icelandic Horses, I want to automatically upload the results from our Synology NAS to a remote webserver. The program we use automatically generates the html-files that needs to be uploaded.
What is the easiest way to achieve this? I have SSH access on both the NAS and the webserver.
Any help is appreciated :)
In this case you can create a cron task in the synology console with the command:
sudo -i
vi /etc/crontab
Edit the file and add a line like this at the end of the file with a scp command:
0 0 * * * root scp -r "-i/root/.ssh/mykey" 'root#serverurl.com:/some/remote/path' '/some/local/path'
Finally you have to reload the configuration restarting the service with:
synoservice -restart crond
Before all this you must to configure a pair keys to avoid the password entry:
cd to a private directory of the user which will be running the script (typically "$HOME/.ssh", to be created if needed). That directory must be protected to write acces from other users, fix the modes if needed.
generate the keypair using command "ssh-keygen"
("/usr/syno/bin/ssh-keygen" if not in your PATH)
at the prompt "Enter file in which to save the key", choose a file
name (let's say "mykey")
at the prompt "Enter passphrase (empty for no passphrase):" press
return (this will create a passwordless private key)
Two files will be created: "mykey" and "mykey.pub"
copy the contents of mykey.pub inside "$HOME/.ssh/authorized_key"
file of user account on the remote machine your script is going to
connect to.
in your script, add "-i" as argument to the
ssh command
Also in this forum is explained how to make the copy with rsync instead of scp

Issue remoting into a device and doing a simple ping test with Ansible

After following instructions both online and in a couple of books, I am unsure of why this is happening. I have a feeling there is a missing setting, but here is the setup:
I am attempting to use the command:
ansible all -u $USER -m ping -vvvv
Obviously using the -vvvv for debugging, but not much output aside from the fact it says it's attempting to connect. I get the following error:
S4 | FAILED => FAILED: Authentication failed.
S4 stands for switch 4, a Cisco switch I am attempting to automate configuration and show commands on. I know 100% the password I set in the host_vars file is correct, as it works when I use it from a standard SSH client.
Here are my non-default config settings in the ansible.cfg file:
[defaults]
transport=paramiko
hostfile = ./myhosts
host_key_checking=False
timeout = 5
My myhosts file:
[cisco-switches]
S4
And my host_vars file for S4:
ansible_ssh_host: 192.168.1.12
ansible_ssh_pass: password
My current version is 1.9.1, running on a Centos VM. I do have an ACL applied on the management interface of the switch, but it allows remote connections from this particular IP.
Please advise.
Since you are using ansible to automate commands in a Cisco switch, I guess you want to perform the SSH connection to the switch without been prompted for password or been requested to press [Y/N] to confirm the connection.
To do that I recommend to configure the Cisco IOS SSH Server on the switch to perform RSA-Based user authentication.
First of all you need to generate RSA key pair on your Linux box:
ssh-keygen -t rsa -b 1024
Note: You can use 2048 instead 1024 but consider that some IOS versions will accept maximum 254 characters for ssh public key.
At switch side:
conf t
ip ssh pubkey-chain
username test
key-string
Copy the entire public key as appears in the cat id_rsa.pub
including the ssh-rsa and username#hostname.
Please note that some IOS versions will accept
maximum 254 characters.
You can paste multiple lines.
exit
exit
If you need that 'test' user can execute privileged IOS commands:
username test privilege 15 secret _TEXT_CLEAR_PASSWORD_
Then, test your connection from your Linux box in order to add the switch to known_hosts file. This will only happen one time for each switch/host not found in the known_hosts file:
ssh test#10.0.0.1
The authenticity of host '10.0.0.1 (10.0.0.1)' can't be established.
RSA key fingerprint is xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:d6:4b:d1:67.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '10.0.0.1' (RSA) to the list of known hosts.
ciscoswitch#
ciscoswitch#exit
Finally test the connection using ansible over SSH and raw module, for example:
ansible inventory -m raw -a "show env all" -u test
I hope you find it useful.

How to do remote ssh non-interactively

I am trying to connect to a remote host from my local host through the below command.But there was a setting in the remote host that soon after we login it will prompt to enter a badge ID,password and reason for logging in, because it was coded like that in profile file on remote-host How can I overcome those steps and login directly non-interactively, without disturbing the code in profile.
jsmith#local-host$ ssh -t -t generic_userID#remote-host
Enter your badgeID, < exit > to abort:
Enter your password for <badgeID> :
Enter a one line justification for your interactive login to generic_userID
Small amendment: to overcome remote server expect approach is required, but in case local script connects to bunch of remote servers, which configuration may be broken, just use SSH options:
ssh -f -q -o BatchMode=yes -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null USER#TARGETSYSTEM
This will omit ask for password in case there is no ssh_key setup, exit silently and continue with script/other hosts.
Puts ssh to background with -f, which is required when calling ssh command from sh (batch) file to remove local console redirect to remote input (implies -n).
Look into setting up a wrapper script around expect. This should do exactly what you're looking for.
Here are a few examples you can work from.
I have upvoted Marvin Pinto's answer because there is every reason to script this, in case there are other features in the profile that you need, such as Message of the Day motd.
However, there is a quick and dirty alternative if you don't want to make a script and you don't want other features from the profile. Depending on your preferred shell on the remote host, you can insist that the shell bypasses the profile files. For example, if bash is available on the remote host, you can invoke it with:
ssh -t -t generic_userID#remote-host bash --noprofile
I tested the above on the macOS 10.13 version of OpenSSH. Normally the command at the end of the ssh invocation is run non-interactively, but the -t flag allows bash to start an interactive shell.
Details are in the Start-up files section of the Bash Reference Manual.

Smart way to copy multiple files from different paths using scp [duplicate]

This question already has answers here:
scp or sftp copy multiple files with single command
(19 answers)
Closed last year.
I would like to know an easy way to use scp to copy files and folders that are present in different paths on my file system. The SSH destination server requests a password and I cannot put this in configuration files. I know that scp doesn't have a password parameter that I could supply from a script, so for now I must copy each file or directory one by one, writing my password every time.
in addition to the already mentioned glob:
you can use {,} to define alternative paths/pathparts in one single statement
e.g.: scp user#host:/{PATH1,PATH2} DESTINATION
From this site:
Open the master
SSHSOCKET=~/.ssh/myUsername#targetServerName
ssh -M -f -N -o ControlPath=$SSHSOCKET myUsername#targetServerName
Open and close other connections without re-authenticating as you like
scp -o ControlPath=$SSHSOCKET myUsername#targetServerName:remoteFile.txt ./
Close the master connection
ssh -S $SSHSOCKET -O exit myUsername#targetServerName
It's intuitive, safer than creating a key pair, faster than creating a compressed file and worked for me!
If you can express all the names of the files you want to copy from the remote system using a single glob pattern, then you can do this in a single scp command. This usage will only support a single destination folder on the local system for all files though. For example:
scp 'RemoteHost:/tmp/[abc]*/*.tar.gz' .
copies all of the files from the remote system which are names (something).tar.gz and which are located in subdirectories of /tmp whose names begin with a, b, or c. The single quotes are to protect the glob pattern from being interpreted from the shell on the local system.
If you cannot express all the files you want to copy as a single glob pattern and you still want the copy to be done using a single command (and a single SSH connection which will ask for your passsword only once) then you can either:
Use a different command than scp, like sftp or rsync, or
Open an SSH master connection to the remote host and run several scp commands as slaves of that master. The slaves will piggyback on the master connection which stays open throughout and won't ask you for a password. Read up on master & slave connections in the ssh manpage.
create a key pair, copy the public key to the server side.
ssh-keygen -t rsa
Append content inside the file ~/.ssh/identity.pub to file ~/.ssh/authorized_keys2 of server side user. You need not to type password anymore.
However, be careful! anybody who can access your "local account" can "ssh" to the server without password as well.
Alternatively, if you cannot use public key authentication, you may add the following configuration to SSH (either to ~/.ssh/config or as the appropriate command-line arguments):
ControlMaster auto
ControlPath /tmp/ssh_mux_%h_%p_%r
ControlPersist 2m
With this config, the SSH connection will be kept open for 2 minutes so you'll only need to type the password the first time.
This post has more details on this feature.