sjwarner
sjwarner

Reputation: 462

Bash script to ssh to particular server

I'm wondering how I would go about creating my own bash script to ssh to a server. I know it's lazy, but I would ideally want not to have to type out:

ssh username@server

And just have my own two letter command instead (i.e. no file extension, and executable from any directory).

Any help would be much appreciated. If it helps with specifying file paths etc, I am using Mac OS X.

Upvotes: 1

Views: 1223

Answers (4)

Alvaro Gutierrez Perez
Alvaro Gutierrez Perez

Reputation: 3877

You can use ssh-argv0 to avoid typing ssh.

To do this, you need to create a link to ssh-argv0 with the name of the host you want to connect, including the user if needed. Then you can execute that link, and ssh will connect you to the host of the link name.

Example

Setup the link:

ln -s /usr/bin/ssh-argv0 ~/bin/my-server
  • /usr/bin/ssh-argv0 is the path of ssh-argv0 on my system, yours could be different, check with which ssh-argv0
  • I have put it in ~/bin/ to be able to execute it from any directory (in OS X you may need to add ~/bin/ manually to your path on .bash_profile)
  • my-server is the name of my server, and if needed to set the user, it would be user@my-server

Execute it:

my-server

Even more

You can also combine this with mogeb answer to configure your server connection, so that you can call it with a shorter name, and avoid to include the user even if it is different than on the local system.

Host serv
    HostName my-server
    User my-user
    Port 22

then set a link to ssh-argv0 with the name serv, and connect to it with

serv

Upvotes: 2

jvdh
jvdh

Reputation: 612

you could create an alias like this:

alias ss="ssh username@server" and write it into your .bash_profile. ".bash_profile" is a hidden file is located in your home directory. If .bash_profile doesn't exist yet (check by typing ls -a in your home directory), you can create it yourself.

The bash_profile file will be read and executed every time you open a new shell.

Upvotes: 1

Mr. Llama
Mr. Llama

Reputation: 20889

Use an alias.

For example: alias sv='ssh user@hostname', then you can simply type sv.
Be sure to put a copy of the aliases in your profile, otherwise they will disappear at the end of your session.

Upvotes: 5

mogeb
mogeb

Reputation: 189

You can set configs for ssh in file ~/.ssh/config:

Host dev
    HostName mydom.example.com
    User myname

Then, just type

$> ssh dev

And you're done. Also, you can add your public key to the file ~/.ssh/authorized_keys so you won't get prompted for your password every time you want to connect via ssh.

Upvotes: 11

Related Questions