Unix SSH without password - mysql

Hey all I'm completely new to Unix and I need to write up a "shell script" (?) to connect to another terminal and run a few SQL queries. How on earth do I do this? I've been browsing a few answers from this and other boards and if I have found my answer I don't understand it.
I am able to manually connect, enter password, etc, but I need to automate the process. I don't have access to Perl (as a few answers have suggested) and I am unable to edit the etc/shadow file. So I assume this has to be done strictly through Unix itself. This is what I am currently using:
X=`vUser='USER-NAME'
vPass='PASSWORD'
vTable='TABLENAME'
vHOST='HOST-NAME'
vPORT=4443
ssh root#vHost
expect {
"root#the-host password:"{
send -s "'vPass'\r"
}
}
SQL_Query='select * from vTable limit 10'
mysql -p$vPASS -D$vTable -u$vUser P$vPort<<EOF
$SQL_Query
EOF`
echo $X>Output.dat
Please explain all answers in full. I'm trying to learn.

Might not be a 100% relevant but I had to do the same on Linux.
First off you want to make a new user account on the other server that has SSH access and generate an SSH keypair, even if you're going to do this as root, keypairs are far superior over standard passwords because they're stronger, and they allow you to log in automatically over SSH.
There's no real way of automating the password entry process (at least, not on Linux), hence the reason SSH keys are required to do this.
You can basically send a chain of commands as a parameter to the SSH tool.
Like so,
ssh user#host "ls; cat *; yes;"
Hope that helped.

Try this:
Copy your SSH public key to your clipboard (output of cat ~/.ssh/id_rsa.pub). If you don't have an SSH key pair then generate it with this tutorial.
Paste your public key to your server's ~/.ssh/authorized_keys file. If it doesn't have one, create it with nano ~/.ssh/authorized_keys and paste it there.
In your computer, you can run the script in the server with the following command:
ssh user#server_ip 'bash -s' < local_script.sh
Or if you have a single command to run then this will do:
ssh user#server_ip "echo Test | tee output.log"
If you don't like SSH asking you for the password all the time, use ssh-agent
For SQL-specific scripts, you can put all your SQL commands in a single file, say query.sql. You should copy query.sql to your server (scp query.sql user#server_ip:~/) and then run
ssh user#server_ip "mysql -uyourusername -pyourpassword < query.sql | tee output.log"
The output will be saved in output.log. Check this answer too.

There is a Linux command ssh-copy-id will do this for you, it is also available to Mac as a homebrew formula.

Related

SnowSQL: Cache credentials

I have to use SSO to authenticate, which I do via a browser. I run queries with:
$ snowsql -a <ACCOUNT> -u <USERNAME> -r <ROLE> --authenticator externalbrowser -f foo.sql
However, this requires me to do the annoying browser authentication process every time. I know that account/user/role can be put in the config, those are not the problem since I often change all three - but I'd like to avoid having to open/close the browser for SSO auth every time I run a query.
Is there a way to make SnowSQL cache the credentials, so that on repeated runs like this, I don't have to reauthenticate?
Key pair authentication is documented here: https://docs.snowflake.com/en/user-guide/key-pair-auth.html
In my view it is the best solution when using the CLI and you want the authorisation steps to be as minimal as possible

How to convert bash file to a binary executable

I created a binary executable from bash script on linux server through SHC. The binary created works fine on linux machines, but through mistake on Mac. How could I convert my bash file to binary executable that is able to run everywhere(ubuntu, CentOS, Mac, Cygwin)?
shc -v -r -T -f ir16fetcher.sh
mv ir16fetcher.sh.x ir16fetcher
Shebang of my bash script
#!/bin/bash
On Linux machines
./ir16installer
USAGE : ir16fetcher <servername/ip address> [the n th latest build - optional. Default 1]
EXAMPLE: ir16fetcher jagger 2
EXAMPLE: ir16fetcher 167.116.6.155
REQUIRE: Please make sure conf file in installation folder ~/IRinstall/ir16 & ~/IRinstall/irmanager
On my Mac
./ir16installer
-bash: ./ir16installer: cannot execute binary file
I think it's not gonna work
"The compiled binary will still be dependent on the shell
specified in the first line of the shell code (i.e.
#!/bin/sh), thus shc does not create completely independent
binaries."
From http://www.datsi.fi.upm.es/~frosal/sources/shc.html
You will have to do this for every architecture and operating system you need to support. In any case, there doesn't really seem to be any benefits of using this method for distribution. It adds dependencies and complicates delivery, and I'm pretty sure whatever obfuscation the "shc" compiler implements is easily reversed.
if the goal here is to "hide" your source code, and then have the "hidden" copy of the code be executable on the Unix OSes you listed, then, encryption is really your only option.
I say this because encryption tools are available on every base Unix install. For your purposes, this is a very good thing as you wont have to download or configure anything additional. They're just there, as part of the natural installation of the OS. One of such tools is called openssl.
To Encrypt your file/script with openssl:
echo precious-content | openssl aes-128-cbc -a -salt -k mypassword
U2FsdGVkX1+K6tvItr9eEI4yC4nZPK8b6o4fc0DR/Vzh7HqpE96se8Fu/BhM314z
To Decrypt your file/script with openssl:
echo U2FsdGVkX1+K6tvItr9eEI4yC4nZPK8b6o4fc0DR/Vzh7HqpE96se8Fu/BhM314z | openssl aes-128-cbc -a -d -salt -k mypassword
precious-content
Now, to get openssl to do what you want it to do automatically without having to spend hours of your own time figuring out a way, you can paste your script to a site like www.EnScryption.com. This site will generate an "executable" version of your code for you, which you can then run on any Mac, Ubuntu, RedHat, CentOS box.

send spawn id exp4 not open error in expect

My ultimate goal is to do telnet to a router and interact with it. The following expect script does not help me at all. The router does not have any user id or pasword. it is automatic login.
Expect file code.
set iptotelnet "10.x.x.x"
spawn telnet $iptotelnet
sleep 10
expect ">" #this is because initially the prompt will be >
sleep 10
send "enable\r" # this should change the prompt from > to #
sleep 10
expect "#"
sleep 10
interact
sleep 10
exit
However, I get the following error.
send: spawn id exp4 not open
while executing
send "enable\r".
This is not just with telnet, i get the same error with any other command also.
please help me.
Your script has no major issues with it, not that would cause spawn to fail like that. (The comments you have would cause problems, but are trivially fixable by using ;# instead of #.) Therefore your problem lies elsewhere (well, with very high probability).
I see that you are trying to control telnet with Expect on Windows. Alas, telnet is a special case that can't be controlled this way — Expect on Windows uses the system debugging facilities to intercept terminal output, but this doesn't work for executables that have special system permissions set, and telnet is one of the programs for which this is true — so you need another approach. The simplest is to get plink.exe (which is really PuTTY for terminals/automation) and to use that (in “telnet” mode) instead of telnet.
Probably you can't use # comments in send command line.
Try same but without comment in send string.
It happens to me too. And it has been resolved.
I try to automatically telnet a server in the Cygwin on Windows.
But the Microsoft telnet installed in Windows won't work in a Cygwin shell
If you got the response below, this is the source of your problems type:
$ which telnet
/cygdrive/c/WINDOWS/system32/telnet
There are two solutions:
1. For Cygwin x86, just simply install the package "inetutil" which includes telnet command.
2. For Cygwin x86_64, currently(2013-09-09) the "inetutil" hasn't been port to 64bit, so I use the plink.exe which is part of PuTTy instead

Cannot login to phpMyAdmin, no errors shown

I have MySQL set up correctly on my linux computer, however I want a better way to input data into the database besides terminal. For this reason, I downloaded phpMyAdmin. However, when I try to log in to the phpMyAdmin from index.php, it doesnt do anything. It seems to just refresh the page without doing anything. I am putting in the correct MySQL username and password. What is the issue?
Here is a screen shot of what it shows after I click "go".
This is a possible issue when the path to save php_session is not correctly set :
The directory for storing session does not exists or php do not have sufficient rights to write to it.
To define the php_session directory simply add the following line to the php.ini :
session.save_path="/tmp/php_session/"
And give write rights to the http server.
usually, the http server run as user daemon in group daemon. If it is the case, the following commands will make it :
chown -R :daemon /tmp/php_session
chmod -R g+wr /tmp/php_session
service httpd restart
Login fails if session folder in not writeable. To check that, create a PHP file in your web directory with:
<?php
$sessionPath = 'undefined';
if (!($sessionPath = ini_get('session.save_path'))) {
$sessionPath = isset($_ENV['TMP']) ? $_ENV['TMP'] : sys_get_temp_dir();
}
if (!is_writeable($sessionPath)) {
echo 'Session directory "'. $sessionPath . '"" is not writeable';
} else {
echo 'Session directory: "' . $sessionPath . '" is writeable';
}
If session folder is not writeable do either
sudo setfacl -R -m u:www-data:rwx <session directory> or chmod 777 sudo setfacl -R -m u:www-data:rwx <session directory>
-
I am late to the game, but on Amazon linux AMI I could not log in to phpmyadmin ... it just kept refreshing the login screen with no errors.
I have fixed with below command
sudo chmod -R 755 /var/lib/php/session
I fixed my issue on CentOS 7 with MariaDB and phpmyadmin I downloaded from offical phpmyadmin site by adding
session.save_path = "/var/lib/php/session"
to /etc/php.ini
and
chown -R :lighttpd /var/lib/php/session
I also restarted php-fpm and lighttpd after
In my case the solution was to set an Apache setting properly:
ProxyPassReverseCookiePath
This was required, because ProxyPass and ProxyPassReverse were in use, but cookie paths are not changed automatically.
It'd be great if PHPMyAdmin had shown something like session not found or anything, when password is sent with POST.
Do you have a .htaccess file in one of the parent directories that strips off index.php from the url by doing a 301 redirect?
301 redirects discard the form data and redirect you as if you didn't submit anything. So you get returned to the login page.
So you should create a local .htaccess file in the phpmyadmin directory with a single line RewriteEngine On. This will overwrite the previous rewrite rule to nothing.
You may need to clear the browser cache as Chrome aggressively caches 301 redirects.
In my case the hard drive was full.
Use df -h to check the space left on your hard drive, and if you want you can free some space by using the command sudo apt-get clean, which removes installation files.
I hope this will help some future users.
I ran these commands and it worked for me:
sudo service httpd restart
sudo service mysqld stop
sudo service mysqld start
Try searching the web for installation or setup guides for phpMyAdmin. Look at two or three of these and make sure you have covered all the required steps. (If you have already done so, please include which guides you have followed it in the question).
See if it helps to edit config.inc.php (acecoder mentioned this as well).
Check if this guide is of any help.
Which distro are you on? Try searching for the name of the distro you are using together with "phpMyAdmin guide" or "phpMyAdmin setup howto".
If you encounter errors along the way, post the error text here, if it's short (or paste via a pastebin-like site if it's long).
Are you sure that mysql is running? I had the same issue after doing a database import and filling up the volume containing the mysql database. After changing various permissions and clearing sessions, I tried to restart mysql (/etc/init.d/mysql restart) and it failed because the volume was full. After increasing /var and starting mysql successfully, I was able to log into phpmyadmin just fine.
If you have an error like:
Host 'host_name' is blocked because of many connection errors.
Login in your mysql as root and run the flush hosts command
1.- mysql -u root -p
2.- mysql > flush hosts
After this I was able to login again in phpmyadmin
phpMyAdmin will show errors when login fails. If it doesn't, it means that your setup has an error.
The most likely place to check is your php.ini settings. Since there doesn't seem to be an official list of phpMyAdmin-compatible settings, it's mostly trial and error.
Make sure you have enabled the stuff that needs to be enabled. Also check that you did not enable uncommon php.ini settings (like enable_post_data_reading = Off) because phpMyAdmin assumes them to be "the usual ones".
To ease debugging, start with a clean default php.ini file then tweak them line by line to see which setting is causing the error. (Don't forget that you need to restart your server after changing the php.ini file for the changes to take place.)
In my case it was due to an old Apache session.
Stop Apache, clear all pending sessions in your sessions.save_path directory (example: /var/lib/php/session) and restart Apache.
Make sure to set a 32 chars long random key in 'config.inc.php' in the $cfg['blowfish_secret'] value. That solved it for me.
Didn't realize I need to restart MariaDB after modifying config.inc.php:
service mariadb restart
Otherwise at least in my case changes didn't come affect. Also make sure your php session directory is writable by webserver (typically session.save_path = "/var/lib/php/session")

How to config mercurial to push without asking my password through ssh?

I use mercurial in my project, and every time I push new changesets to the server by ssh, it ask me for a password.
Then how to config the mercurial to push with out asking password?
I works on Ubuntu 9.10
On Linux and Mac, use ssh-agent.
Ensure you have an ssh keypair (see man ssh-keygen for details)
Copy your public key (from ~/.ssh/id_dsa.pub) to the remote machine, giving it a unique name (such as myhost_key.pub)
Log in to the remote machine normally and append the public key you just copied to the ~/.ssh/authorized_keys file
Run ssh-add on your local workstation to add your key to the keychain
You can now use any remote hg commands in this session without requiring authentication.
Assuming you're using Windows, have a read of my Mercurial/SSH guide. Down the bottom of the post you'll find info on how to use PuTTy to do this for you.
Edit: -- Here's the part of the post that I'm talking about (bear in mind you'll need to have pageant running with your key already loaded for this to work):
Client: Setting up Mercurial
If you haven't already, make sure you install Mercurial on the client machine using the default settings. Make sure you tell the installer to add the Mercurial path to the system PATH.
The last step of configuration for the client is to tell Mercurial to use the PuTTy tools when using SSH. Mercurial can be configured by a user-specific configuration file called .hgrc. On Windows it can also be called Mercurial.ini. The file is located in your home folder. If you don't know what your home folder is, simply open a command prompt and type echo %USERPROFILE% - this will tell you the path.
If you haven't set up your configuration yet, then chances are the configuration file doesn't exist. So you'll have to create it. Create a file call either .hgrc or Mercurial.ini in your home folder manually, and open it in a text editor. Here is what part of mine looks like:
[ui]
username = OJ Reeves
editor = vim
ssh = plink -ssh -i "C:/path/to/key/id_rsa.ppk" -C -agent
The last line is the key and this is what you need to make sure it set properly. We are telling Mercurial to use the plink program. This also comes with PuTTy and is a command-line version of what the PuTTY program itself does behind the scenes. We also add a few parameters:
-ssh : Indicates that we're using the SSH protocol.
-i "file.ppk" : Specifies the location of the private key file we want to use to log in to the remote server. Change this to point to your local putty-compatible ppk private key. Make sure you user forward-slashes for the path separators as well!
-C : This switch enables compression.
-agent : This tells plink to talk to the pageant utility to get the passphrase for the key instead of asking you for it interactively.
The client is now ready to rock!
Install PuTTY.
If you're on Windows, open projectdir/.hg/hgrc in your favorite text editor. Edit it to look like this:
[paths]
default = ssh://hg#bitbucket.org/name/project
[ui]
username = Your Name <your#email.com>
ssh = "C:\Program Files (x86)\PuTTY\plink.exe" -ssh -i "C:\path\to\your\private_key.ppk" -C -agent
If it's taking forever to push, the server might be trying to ask you a question (but it's not displayed).
Run this:
"C:\Program Files (x86)\PuTTY\plink.exe" -T hg#bitbucket.org -i "C:\Program Files (x86)\PuTTY\plink.exe" -ssh -i "C:\path\to\your\private_key.ppk"
Answer any questions, and then try pushing again.
If you're using Bitbucket, open your private key with puttygen, copy your public key out of the top textbox, and add it to your user account: https://bitbucket.org/account/user/USERNAME/ssh-keys/