scp error--syntax, or something else? - scp

I am trying to use scp to copy various files from my work machine to my personal. I use the code:
scp usernamework#workcomputer:~/directory/to/file \
usernamepersonal#personalcomputer:~/Directory/to/copied/file
When I enter the code I am prompted for my work computer password. I enter the password and the error is:
could not resolve hostname(personal computer)
Is there a syntax error in my code-or is there something else going on?

If you specify two remote hosts, it will connect to the first one and from there it will connect to the second one. The second hostname is probably not resolvable/visible from the first one and therefore it fails. There are few possibilities you can do:
Connect to your personal computer and do a transfer with only one remote:
scp usernamework#workcomputer:~/directory/to/file ~/Directory/to/copied/file
Use -3 switch, which will connect to both of the ends from your current computer:
scp -3 usernamework#workcomputer:~/directory/to/file \
usernamepersonal#personalcomputer:~/Directory/to/copied/file

Related

VScode remote connection error: The process tried to write to a nonexistent pipe

I use vscode with remote-ssh to connect my server, after configuring, I want to connect my host, but it failed, the dialog box display:"could not establish connection to XX, The process tried to write to a nonexistent pipe."
output:
[16:45:20.916] Log Level: 3
[16:45:20.936] remote-ssh#0.49.0
[16:45:20.936] win32 x64
[16:45:20.944] SSH Resolver called for "ssh-remote+aliyun", attempt 1
[16:45:20.945] SSH Resolver called for host: aliyun
[16:45:20.945] Setting up SSH remote "aliyun"
[16:45:21.012] Using commit id "c47d83b293181d9be64f27ff093689e8e7aed054" and quality "stable" for server
[16:45:21.014] Install and start server if needed
[16:45:21.019] Checking ssh with "ssh -V"
[16:45:21.144] > OpenSSH_for_Windows_7.7p1, LibreSSL 2.6.5
[16:45:21.214] Running script with connection command: ssh -T -D 5023 aliyun bash
[16:45:21.221] Terminal shell path: C:\WINDOWS\System32\cmd.exe
[16:45:21.504] >
>
>
> ]0;C:\WINDOWS\System32\cmd.exe
[16:45:21.505] Got some output, clearing connection timeout
[16:45:21.577] >
>
>
>
[16:45:21.592] > Bad owner or permissions on C:\\Users\\DY/.ssh/config
>
[16:45:21.689] > The process tried to write to a nonexistent pipe.
>
[16:45:22.091] "install" terminal command done
[16:45:22.092] Install terminal quit with output: The process tried to write to a nonexistent pipe.
[16:45:22.093] Received install output: The process tried to write to a nonexistent pipe.
[16:45:22.096] Resolver error: The process tried to write to a nonexistent pipe
[16:45:22.107] ------
Add the absolute file path to a custom SSH config file(C:\Users\{USERNAME}\.ssh\config), and my problem is solved.
If you format/re-install Server OS, but use same IP as before,
you may encounter fingerprint mismatched.
You may need to delete old fingerprint in this file:
C:\Users\xxx.ssh\known_host
and old IP in the file:
C:\Users\xxx.ssh\config
Then try to add host again.
What worked for me:
delete ssh config folder both in C:\Program Data\ssh and C:\<user>\.ssh
In VS Code, press F1, choose Remote-SSH: Connect to Host...
Do NOT enter anything in the prompt, but instead choose + Add New SSH Host..
Enter the full ssh command, including the key (in case of Windows,
you may want to enclose the path with double quote mark) ssh -i "C:\path\to\key" user#host. (you need to make sure the key has a limited permission. Remove all inherited permissions, and only give a full control to the owner.)
You will be asked to choose a folder in which a new config file will be created. Choose any of the two options.
There will a prompt notifying that the new config file
has been created. Click connect
At least three things may be happening:
Option 1
The location of your config file is not the absolute location, meaning you are probably using the location of the folder where the config file is.
If that is the case, access your User Settings in VSCode. Scroll to the Extensions>Remote - SSH. And add config at the end of the absolute file path of your custom SSH config file. In Windows, it can be
C:\Users\user\.ssh\config
See image below
Option 2
Authentication problems.
If that is the case, one of the things that may solve is generating new SSH keys.
In Windows, for that, I recommend using MobaXterm.
In MobaXterm, open a new terminal and write
ssh-keygen -b 4096 -t rsa
Then, in the config file, make sure that the IdentityFile points to the location of the key. MobaXterm's home directory, usually, is C:\Users\user\Documents\MobaXterm. If it makes it easy, one can copy/move the keys to C:\Users\user\.ssh and then just add, in the config file, IdentityFile ~/.ssh/KEY_rsa (where KEY_rsa is the name of the [public] key).
Note that if you use PuTTY to generate the keys, on the server OpenSSH authorized_keys file, one doesn't want the public key that one saves, but the one that appears on top (see image bellow):
Option 3
Your config file may be wrong.
The config file tends to look as follows. Double check if the fields have the information needed for the connection to be established.
Host Test # This is the name we want to give the host
User user # This is the username
Hostname blabla.com # This is the hostname
PreferredAuthentications publickey
IdentityFile ~/.ssh/KEY_rsa # This is the location of the key
IdentitiesOnly yes
Port 50 # This varies
What worked for me was to delete all of the contents of folder: C:\Users\MYNAME.ssh That meant to delete both the config file and known-hosts. The config was probably the most important one to delete.
The solution in my case was editing the json settings file for VSC as shown here: https://code.visualstudio.com/docs/remote/troubleshooting#_troubleshooting-hanging-or-failing-connections
In VSC go to File, Preferences, Setting and click on the upper right hand icon (Open Settings, JSON). Add these two lines to settings.json and retry connecting:
"remote.SSH.showLoginTerminal": true,
"remote.SSH.useLocalServer": false
In my case I had another setup:
Git bash in Windows was configured and I am using the ssh.exe provided by this tool
In the "Remote SSH" extension in VSCode, I specified the full path of this ssh.exe
I am using multiple servers (with ProxyJump)
The error message is the same as the OP but in the logs it was written that the ssh config file was not found, where all the folder names was concatenated (because it did not recognize the windows path separator)
Problem: the ssh.exe is using a different path convention thant VSCode. ssh.exe is using the "/c/Users/..." pattern and VSCode is using the "C:\Users..." pattern.
Solution:
Make sure the SSH config is at a standard place (C:\Users\LOGIN\.ssh\config)
Remove the absolute path of the config file in the "Remote SSH" settings in VSCode
VSCode will still be able to access the settings using the standard path, and the ssh.exe configuration will still look at the same standard path so the connexion is working.
Note:
I have the error only when connecting with multiple ssh servers (using ProxyJump). When connecting only to the first server, the solution of #pszrux and this one are both working for me.
This is probably something everyone has tried before looking here, but it worked for me. The server I was trying to ssh into was not responding, leading to the nonexistant pipe error. I rebooted the server and everything worked fine.
OS: windows 10
In my case there were permission issues. Repeatedly changing inheritance in windows did not solve the issue. Finally this worked
change the folder in which the config file is stored.
From C:/users/usr/.ssh/config to D:/config
and changed the config path in vscode remote ssh settings.
This worked for me.
This seems to be a problem with varied causes and corresponding remedies. In my case the problem had to do with the version of ssh I was using. In my Windows path there were two places were an instance of ssh.exe resided:
C:\Program Files (x86)\OpenSSH\bin
C:\WINDOWS\System32\OpenSSH\
After using both paths to set the "Remote.SSH: Path" parameter (which is in "Remote.SSH: Settings" [see here]), i.e. first C:\Program Files (x86)\OpenSSH\bin\ssh.exe and then C:\WINDOWS\System32\OpenSSH\ssh.exe, the problem still persisted.
Then I looked at this and tried the git-provided ssh.exe, which I already had on my system (otherwise, just install git, it's good stuff anyway :) )
Setting the SSH path parameter with that version did the trick for me, i.e. setting path to:
C:\Program Files\Git\usr\bin\ssh.exe
In my case, I did what dalilander said, but instead of deleting the entire '.ssh' folder, I just needed to delete the file 'known_hosts' and then it worked. So the servers I had saved were not deleted.
The path of that folder is C:\Users\yourUsername\.ssh
For Windows:
Adding the escape character before the private key file name & using quotes around the path solved my issue.
//config file
Host 12.12.12.12
HostName 12.12.12.12
IdentityFile "C:\Users\USERNAME/\PRIVATEKEY" <----Note /\
User username
Trying to add the full path in "IdentityFile" made the trick
" IdentityFile C:\Users\xxx.ssh\xxx"
The solution below may be the last resort but it perfectly solved the issue for me in a Windows 10 local machine. I simply delete the known_hosts file under the directory C:\Users\[your-username]\.ssh, relaunch VS Code and reconnect the remote server through Remote Explorer. Everything works normally afterward.
This seems to be a general error when the ssh connection fails for one of a multitude of reasons.
Adding what my issue was, and what helped, because I don't see it in the other answers in here: I had re-installed the box I was connecting to, and with it, reset the key it was using to authenticate. The ssh process tried to connect and failed with the usual "someone might be MITMing you this very moment, the identification changed" error, visible in the VSCode terminal. Solution was to go to my authorized_keys file and remove the offending key.
Obviously only know that if you know for sure why the identification changed, and that it's harmless. Don't actually get MITMed.
I had this problem once.
All you need to do is,
Go to /Users/XXX/.ssh
if you are on the windows, use command : "del /f known_hosts" to delete the known_hosts on the command prompt.
3.Then go to C:\Users\XXX.ssh\config on the vs code( config file )
4.Delete the host and the user if the host that you are trying to connect to is already there.
5.Then try to connect to the new host as usual.This will work.
The problem here could the mismatch of the finger prints once you reinstall the OS o n your host machine.
So to solve this problem by deleting the host that was saved.
once the config file on the vs code is edited it should look like..below picture is to show how the config file should look(after deleting the host saved)
If you're using WSL and might think that you should update ~/.ssh/config, that might not be the case.
Copy the content from ~/.ssh/config
Append it to C:\User\xxx\.ssh\config windows file
Make sure the public/private key is on C:\User\xxx\.ssh\ and is listed in config
Reconnect
Had an existing(working) configuration and had the same error when I added a new one. What worked for me is instead of just adding a new host configuration, I also commented out the first working config. Didn't know what happened but it worked.
In my case this was an offending key in my known_hosts in Windows (vscode on windows, remote developing via ssh on linux).
The error that comes back in vscode is not explaining in any way.
In my case, the path to key file was wrong.
For me, (windows) the permissions on the .pem file were the Critical issue. I had Administrator group only on the pem file and it was not working. I had to explicitly add the Admin user as well (even though admin is of course in administrator group).
In my case, I had no internet connection.
I was connecting to the server via VPN but the remote configuration was incorrect and I couldn't access the server. (DNS related issues) The connection indicator was showing no errors, so I didn't think of that at first.
Oops :)
I really didn't want to delete my C:Users\valo\.ssh\config, so I played a little with the various entries. It turned out that for me the option IdentitiesOnly yes was the problem. I also disabled security inheritance on all key files in the .ssh folder and left only myself, with Full Rights. Here is what my C:Users\valo\.ssh\config looks like now:
CanonicalizeHostname yes
Host aws.r3
HostName 3.31.45.216
ForwardAgent yes
User ubuntu
IdentityFile C:Users\valo\.ssh\u1-client-20210203-090555.pem
# IdentitiesOnly yes # VSCode Remote doesn't like this flag...?
Host github
HostName github.com
User git
IdentityFile ~/.ssh/id_val_ed25519
Host github.vm
HostName github.com
User git
IdentityFile ~/.ssh/id_valo_ed25519
Host *
ForwardAgent yes
AddKeysToAgent yes
LogLevel FATAL
ChallengeResponseAuthentication no
Now I can connect to aws.r3 with VSCode Remote.
A possible solution:
First run cat $HOME/.ssh/id_rsa.pub on your computer. That will get you a key. Save this key somewhere.
Then open this file by running vim $HOME/.ssh/authorized_keys on the computer that you're are ssh'ing to. Then copy the key in a new line of this file and close it by typing :wq.
You are all set.
In my case it was because the name I gave the host in config was myuser#myhostname. So if your config file looks like this:
Host myuser#myhostname
HostName 12.64.88.234
User myuser
Port 22
Try changing it to this:
Host myuser
HostName 12.64.88.234
User myuser
Port 22
Mine was solved by adding ".pem" extension while specifying the private key.
Here's the sample config text for reference.
Host ec2-3-234-8-176.compute-1.amazonaws.com
HostName ec2-3-234-8-176.compute-1.amazonaws.com
IdentityFile ~/.ssh/privatekey.pem
User username
There can be several reasons that have nothing to do with the accepted answer. For me:
Ubuntu 14.04.1 LTS didn't seem to work
Issues with EC2 auth, see pem file config and pem file permissions
And for yet another seeming cause/solution:
Adding the config path explicitly to settings only caused an EISDIR error.
Removing the listing from known_hosts made it need to confirm the fingerprint, but it didn't provide a way to do that. I could see it trying in the terminal output.
The solution a coworker recommended was to delete the vscode-server files from the server. That was the key step in my case. But...
Connecting to the server using another client, I attempted to rm -rf ~/.vscode-server. I could not delete many of the files because "device or resource busy".
That eventually required doing the following:
fuser ~/.vscode-server/[one of the child files ...]. But, you can probably skip this, because mainly I needed to know what to search for. Plus, fuser and lsof were finicky about returning results -- they often just sit waiting for something, I don't know what.
ps -e | grep node since node is the running process using vscode-server files.
For each PID in the list of node processes from step 2, run ps -o user= -p PID, substituting PID with each process PID in turn. This creates a formatted list of the process's associated user.
This is to determine which node processes you own, so you're not even trying to kill anybody else's.
Starting with the lowest node PID I own, run kill -9 PID. You won't need to run this for all PIDs, because killing a lower PID killed a child PID after a few seconds. So keep checking which node processes still exist after killing one: ps -e | grep node
Finally, once all mine are killed, I can rm -rf ~/.vscode-server
Then, I was able to connect via ssh in VS Code again. And, since I left the fingerprint removed from known_hosts, it even asked to confirm the connection to the server (up top, in the command prompt).
Also, for reference, I left the remote-ssh: settings config file entry, mentioned in other solutions, blank.
For reference or further explanation of certain steps above (I don't intend to elaborate more than I did):
rm: cannot remove ‘.vscode-server/bin/xxxxxx/.nfs000000000xxxxxxxxxxxx’: Device or resource busy
How find out which process is using a file in Linux?
https://unix.stackexchange.com/questions/284934/return-owner-of-process-given-pid/284938
In my case it worked when I added the port in my expression, eg ssh user#host-or-ip -p 22. With '22' the default port number, but you can check which port the ssh system is listening on with the sudo service ssh status command.
WSL Related
In my case, the issue was that my keys were set up on Ubuntu on WSL and VS Code was looking for them in Windows. I copied the keys over from the WSL side to Windows and voila! Worked like a charm!
Steps that I took.
Navigated to the /home//.ssh folder in WSL and then entered explorer.exe .
From there, I copied the id_rsa and id_rsa.pub files and pasted them in the windows side, under C:\Users<username>.ssh
Then I tried connecting again from VS Code and it worked perfectly.

Connect through ssh and scp and type in password automatically

I know this question has already been asked several times but I got another problem. I have a part in my script where I connect through ssh and scp and everytime I run the script it always ask for the password. Most of you would probably answer that I should use expect or sshpass yet I don't have any of this two. I tried running:
compgen -c
and there's no expect and sshpass existing.
Are there any alternative commands? I would really appreciate your help. Thanks
Update: I also can't install any of this since I'm only an ordinary user.
First I logged in to server A as testuser and entered the ff command:
ssh-keygen -d
Do not enter any passphrase.
This will generate files in the folder ~/.ssh/
Then scp the file rsa_id.pub (public key) to server B.
scp ~/.ssh/id_dsa.pub testuser#B:/home/testuser/.ssh/authorized_keys2
Do the same vice versa (if you want access to both). Then you can now transfer from one server to the other without the being asked for your password.
source
If you don't want to set up keys for passwordless access (against the rules?), you can set up "SSH connection sharing".
Insert these lines into your .ssh/config file:
ControlMaster auto
ControlPath /tmp/ssh_%r#%n:%p
ControlPersist 8h
Now, when you log into a server from the machine with that config it will ask you your password the first time, and won't ask again until 8 hours of idle time have passed (so, you'll get asked once per day, usually).
What it's doing is keeping the connection open in the background, and then reusing the same connection for all your SSH sessions. This gives a useful connect-speed boost, and means you don't need to re-authenticate. All-in-all, it's great for accelerating scripted SSH and SCP commands.

cp: cannot create regular file ‘Users/James/Desktop’: No such file or directory

I'm trying to copy a file from a remote server to my desktop and i'm getting the above error. I've SSH'd to the server.
Here is what i'm doing:
deploy#ip-10-91-135-76 /data/project/current/lib/data $ scp customer_record.ods /Users/James/Desktop
I have very limited experience and don't understand what is going on?
Thanks a lot
man scp tells you how to use scp. In particular, most usages look like:
scp [user1#]host1:]file1 [[user2#]host2:]file2
You can omit putting the user in if its the same as your current user, and likewise for the host. Since you've SSH'd onto the server already, the start of your command is okay to be scp customer_records.ods, but the next argument has to include the user name and host of the target machine that you want to copy the file to, namely your home computer. Chances are you actually want to go the other way, since your home computer may not have a publicly accessible IP.
End the SSH session, go back to your home machine.
Do:
scp <user-you-sshd-as>#<server-you-sshd-to>:/data/project/current/lib/data/customer_records.ods /Users/James/Desktop
If you need to specify a private key, you can use the -i option: scp -i <path-to-key> ...

Create script/shortcut to login via ssh

My issue is that everytime I have to login to a given account on a linux server (there are many) I have to go pull a text file not I have to look at the username and ip.
Example: "ssh some_user#xxx.xxx.xxx.x -pxxxxx"
I want to make my life a little easier by creating a shortcut, e.g. "ssh some_user"...
I searched and could not find an answer, likely not using the right terminology.
Thanks!
You can use the ssh client configuration file (.ssh/config). If you have to type ssh -p 1234 mylogin#my.server.with.a.long.name.com, you can populate your config file with
host server
hostname my.server.with.a.long.name.com
user mylogin
port 1234
Then you can simply type ssh server and it will have the same effect. You can have as many entries in your .ssh/config file as you want and even use wildcards (*)
If you are using a recent version of bash, you can furthermore make use of the command_not_found_handle function:
command_not_found_handle () {
if grep "host $1" ~/.ssh/config &>/dev/null; then
ssh $#
else
printf "Sorry: Command not found: $1\n"
return 127
fi
}
Then you can connect simply with
server
I dont know if I understood your problem correct, but a proper ssh config file make life muuuch easier. No IP, no domain, no password, not even a username.
See the man page: http://linux.die.net/man/5/ssh_config
I like things like ssh vm, or scp vm:... no more scp blablubb#192.168.226.xy:...+ passphrase.
Also see ssh-keygen and ssh-copy-id for asymmetric key exchange. Will get you rid of typing passwords.
Generally I recommend to read a ssh tutorial.

Which is the best way to bring a file from a remote host to local host over an SSH session?

When connecting to remote hosts via ssh, I frequently want to bring a file on that system to the local system for viewing or processing. Is there a way to copy the file over without (a) opening a new terminal/pausing the ssh session (b) authenticating again to either the local or remote hosts which works (c) even when one or both of the hosts is behind a NAT router?
The goal is to take advantage of as much of the current state as possible: that there is a connection between the two machines, that I'm authenticated on both, that I'm in the working directory of the file---so I don't have to open another terminal and copy and paste the remote host and path in, which is what I do now. The best solution also wouldn't require any setup before the session began, but if the setup was a one-time or able to be automated, than that's perfectly acceptable.
zssh (a ZMODEM wrapper over openssh) does exactly what you want.
Install zssh and use it instead of openssh (which I assume that you normally use)
You'll have to have the lrzsz package installed on both systems.
Then, to transfer a file zyxel.png from remote to local host:
antti#local:~$ zssh remote
Press ^# (C-Space) to enter file transfer mode, then ? for help
...
antti#remote:~$ sz zyxel.png
**B00000000000000
^#
zssh > rz
Receiving: zyxel.png
Bytes received: 104036/ 104036 BPS:16059729
Transfer complete
antti#remote:~$
Uploading goes similarly, except that you just switch rz(1) and sz(1).
Putty users can try Le Putty, which has similar functionality.
On a linux box I use the ssh-agent and sshfs. You need to setup the sshd to accept connections with key pairs. Then you use ssh-add to add you key to the ssh-agent so you don't have type your password everytime. Be sure to use -t seconds, so the key doesn't stay loaded forever.
ssh-add -t 3600 /home/user/.ssh/ssh_dsa
After that,
sshfs hostname:/ /PathToMountTo/
will mount the server file system on your machine so you have access to it.
Personally, I wrote a small bash script that add my key and mount the servers I use the most, so when I start to work I just have to launch the script and type my passphrase.
Using some little known and rarely used features of the openssh
implementation you can accomplish precisely what you want!
takes advantage of the current state
can use the working directory where you are
does not require any tunneling setup before the session begins
does not require opening a separate terminal or connection
can be used as a one-time deal in an interactive session or can be used as part of an automated session
You should only type what is at each of the local>, remote>, and
ssh> prompts in the examples below.
local> ssh username#remote
remote> ~C
ssh> -L6666:localhost:6666
remote> nc -l 6666 < /etc/passwd
remote> ~^Z
[suspend ssh]
[1]+ Stopped ssh username#remote
local> (sleep 1; nc localhost 6666 > /tmp/file) & fg
[2] 17357
ssh username#remote
remote> exit
[2]- Done ( sleep 1; nc localhost 6666 > /tmp/file )
local> cat /tmp/file
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
...
Or, more often you want to go the other direction, for example if you
want to do something like transfer your ~/.ssh/id_rsa.pub file from
your local machine to the ~/.ssh/authorized_keys file of the remote
machine.
local> ssh username#remote
remote> ~C
ssh> -R5555:localhost:5555
remote> ~^Z
[suspend ssh]
[1]+ Stopped ssh username#remote
local> nc -l 5555 < ~/.ssh/id_rsa.pub &
[2] 26607
local> fg
ssh username#remote
remote> nc localhost 5555 >> ~/.ssh/authorized_keys
remote> cat ~/.ssh/authorized_keys
ssh-rsa AAAAB3NzaC1yc2ZQQQQBIwAAAQEAsgaVp8mnWVvpGKhfgwHTuOObyfYSe8iFvksH6BGWfMgy8poM2+5sTL6FHI7k0MXmfd7p4rzOL2R4q9yjG+Hl2PShjkjAVb32Ss5ZZ3BxHpk30+0HackAHVqPEJERvZvqC3W2s4aKU7ae4WaG1OqZHI1dGiJPJ1IgFF5bWbQl8CP9kZNAHg0NJZUCnJ73udZRYEWm5MEdTIz0+Q5tClzxvXtV4lZBo36Jo4vijKVEJ06MZu+e2WnCOqsfdayY7laiT0t/UsulLNJ1wT+Euejl+3Vft7N1/nWptJn3c4y83c4oHIrsLDTIiVvPjAj5JTkyH1EA2pIOxsKOjmg2Maz7Pw== username#local
A little bit of explanation is in order.
The first step is to open a LocalForward; if you don't already have
one established then you can use the ~C escape character to open an
ssh command line which will give you the following commands:
remote> ~C
ssh> help
Commands:
-L[bind_address:]port:host:hostport Request local forward
-R[bind_address:]port:host:hostport Request remote forward
-D[bind_address:]port Request dynamic forward
-KR[bind_address:]port Cancel remote forward
In this example I establish a LocalForward on port 6666 of localhost
for both the client and the server; the port number can be any
arbitrary open port.
The nc command is from the netcat package; it is described as the
"TCP/IP swiss army knife"; it is a simple, yet very flexible and
useful program. Make it a standard part of your unix toolbelt.
At this point nc is listening on port 6666 and waiting for another
program to connect to that port so it can send the contents of
/etc/passwd.
Next we make use of another escape character ~^Z which is tilde
followed by control-Z. This temporarily suspends the ssh process and
drops us back into our shell.
One back on the local system you can use nc to connect to the
forwarded port 6666. Note the lack of a -l in this case because that
option tells nc to listen on a port as if it were a server which is
not what we want; instead we want to just use nc as a client to
connect to the already listening nc on the remote side.
The rest of the magic around the nc command is required because if
you recall above I said that the ssh process was temporarily
suspended, so the & will put the whole (sleep + nc) expression
into the background and the sleep gives you enough time for ssh to
return to the foreground with fg.
In the second example the idea is basically the same except we set up
a tunnel going the other direction using -R instead of -L so that
we establish a RemoteForward. And then on the local side is where
you want to use the -l argument to nc.
The escape character by default is ~ but you can change that with:
-e escape_char
Sets the escape character for sessions with a pty (default: ‘~’). The escape character is only recognized at the beginning of a line. The escape character followed by a dot
(‘.’) closes the connection; followed by control-Z suspends the connection; and followed by itself sends the escape character once. Setting the character to “none” disables any
escapes and makes the session fully transparent.
A full explanation of the commands available with the escape characters is available in the ssh manpage
ESCAPE CHARACTERS
When a pseudo-terminal has been requested, ssh supports a number of functions through the use of an escape character.
A single tilde character can be sent as ~~ or by following the tilde by a character other than those described below. The escape character must always follow a newline to be interpreted
as special. The escape character can be changed in configuration files using the EscapeChar configuration directive or on the command line by the -e option.
The supported escapes (assuming the default ‘~’) are:
~. Disconnect.
~^Z Background ssh.
~# List forwarded connections.
~& Background ssh at logout when waiting for forwarded connection / X11 sessions to terminate.
~? Display a list of escape characters.
~B Send a BREAK to the remote system (only useful for SSH protocol version 2 and if the peer supports it).
~C Open command line. Currently this allows the addition of port forwardings using the -L, -R and -D options (see above). It also allows the cancellation of existing remote port-
forwardings using -KR[bind_address:]port. !command allows the user to execute a local command if the PermitLocalCommand option is enabled in ssh_config(5). Basic help is avail‐
able, using the -h option.
~R Request rekeying of the connection (only useful for SSH protocol version 2 and if the peer supports it).
Using ControlMaster (the -M switch) is the best solution, way simpler and easier than the rest of the answers here. It allows you to share a single connection among multiple sessions. Sounds like it does what the poster wants. You still have to type the scp or sftp command line though. Try it. I use it for all of my sshing.
In order to do this I have my home router set up to forward port 22 back to my home machine (which is firewalled to only accept ssh connections from my work machine) and I also have an account set up with DynDNS to provide Dynamic DNS that will resolve to my home IP automatically.
Then when I ssh into my work computer, the first thing I do is run a script that starts an ssh-agent (if your server doesn't do that automatically). The script I run is:
#!/bin/bash
ssh-agent sh -c 'ssh-add < /dev/null && bash'
It asks for my ssh key passphrase so that I don't have to type it in every time. You don't need that step if you use an ssh key without a passphrase.
For the rest of the session, sending files back to your home machine is as simple as
scp file_to_send.txt your.domain.name:~/
Here is a hack called ssh-xfer which addresses the exact problem, but requires patching OpenSSH, which is a nonstarter as far as I'm concerned.
Here is my preferred solution to this problem. Set up a reverse ssh tunnel upon creating the ssh session. This is made easy by two bash function: grabfrom() needs to be defined on the local host, while grab() should be defined on the remote host. You can add any other ssh variables you use (e.g. -X or -Y) as you see fit.
function grabfrom() { ssh -R 2202:127.0.0.1:22 ${#}; };
function grab() { scp -P 2202 $# localuser#127.0.0.1:~; };
Usage:
localhost% grabfrom remoteuser#remotehost
password: <remote password goes here>
remotehost% grab somefile1 somefile2 *.txt
password: <local password goes here>
Positives:
It works without special software on either host beyond OpenSSH
It works when local host is behind a NAT router
It can be implemented as a pair of two one-line bash function
Negatives:
It uses a fixed port number so:
won't work with multiple connections to remote host
might conflict with a process using that port on the remote host
It requires localhost accept ssh connections
It requires a special command on initiation the session
It doesn't implicitly handle authentication to the localhost
It doesn't allow one to specify the destination directory on localhost
If you grab from multiple localhosts to the same remote host, ssh won't like the keys changing
Future work:
This is still pretty kludgy. Obviously, it would be possible to handle the authentication issue by setting up ssh keys appropriately and it's even easier to allow the specification of a remote directory by adding a parameter to grab()
More difficult is addressing the other negatives. It would be nice to pick a dynamic port but as far as I can tell there is no elegant way to pass that port to the shell on the remote host; As best as I can tell, OpenSSH doesn't allow you to set arbitrary environment variables on the remote host and bash can't take environment variables from a command line argument. Even if you could pick a dynamic port, there is no way to ensure it isn't used on the remote host without connecting first.
You can use SCP protocol for tranfering a file.you can refer this link
http://tekheez.biz/scp-protocol-in-unix/
The best way to use this you can expose your files over HTTP and download it from another server, you can achieve this using ZSSH Python library,
ZSSH - ZIP over SSH (Simple Python script to exchange files between servers).
Install it using PIP.
python3 -m pip install zssh
Run this command from your remote server.
python3 -m zssh -as --path /desktop/path_to_expose
It will give you an URL to execute from another server.
In the local system or another server where you need to download those files and extract.
python3 -m zssh -ad --path /desktop/path_to_download --zip http://example.com/temp_file.zip
For more about this library: https://pypi.org/project/zssh/
You should be able to set up public & private keys so that no auth is needed.
Which way you do it depends on security requirements, etc (be aware that there are linux/unix ssh worms which will look at keys to find other hosts they can attack).
I do this all the time from behind both linksys and dlink routers. I think you may need to change a couple of settings but it's not a big deal.
Use the -M switch.
"Places the ssh client into 'master' mode for connection shar-ing. Multiple -M options places ssh into ``master'' mode with confirmation required before slave connections are accepted. Refer to the description of ControlMaster in ssh_config(5) for details."
I don't quite see how that answers the OP's question - can you expand on this a bit, David?