How to develop on a virtual machine? - macos

I want to edit source code on a virtual machine running Ubuntu. I'm ssh'd into it to preserve my native (mac) key bindings (e.g. copy and paste). Can I route terminal data through to sublime on the host side? Can I invoke the sublime editor in the vm and use it with X11 forwarding?
I'm just looking for the common workflow where I can keep using the key-bindings and editor I've learned to love.

You can use Samba share for this. (Assuming that you are running windows).
That's the way I do it.
How to Create a Network Share Via Samba Via CLI (Command-line interface/Linux Terminal) - Uncomplicated, Simple and Brief Way!
or you can check How to map a network drive?

You have a few options:
You can install Samba for SMB network sharing, or Netatalk for AFP network sharing, as suggested in the answer by Ahmed Daou. Probably the most flexible solution once set up. If you want to get fancy you can also install avahi-daemon so that you can browse to network files from the Finder, as you would any other file share; otherwise you can use "Connect To Server..." from the Finder's Go menu.
You can round-trip it with scp. Install a public-private keypair for SSH so you don't have to enter a password every time out (even if you use a passphrase, your Mac will remember it in its keychain). When you quit Sublime, the saved file will be will copied back to the VM.
Example sublime_open script:
#!/bin/bash
serverAddress="username#myvm.local"
if [[ ! $1 ]]; then
echo "usage: sublime_open <remoteFilename> [username#serverAddress] [serverPort]"
exit 1
fi
[[ $2 ]] && serverAddress="$2"
[[ $3 ]] && serverPort="-P $3" || serverPort=
scp $serverPort $serverAddress:"$1" /tmp/myfile.txt
/Applications/"Sublime Text.app"/Contents/MacOS/"Sublime Text" /tmp/myfile.txt
scp $serverPort /tmp/myfile.txt $serverAddress:"$1"
rm /tmp/myfile.txt &> /dev/null
You can, as you suggested, use X11 and run the Linux version. Install XQuartz on your Mac, and then open an SSH session to your VM with the -X option, e.g. ssh -X myvm.local. Then in that Terminal window run ./sublime_text from whatever directory it lives in (if you install the Ubuntu/Debian package, it appears to be in /opt/sublime_text/sublime_text). It will open in an X window on your Mac.

Related

How to SSH from local linux into specific directory on windows 10 remote

I want to ssh from my local linux computer into a specific directory on a windows 10 remote. The shell that is used on the remote is git bash. I don't want to keep changing the directory every time I log into my remote using ssh.
for linux remotes this is easily done using something like this:
ssh -t user#x.x.x.x "cd /targetDir ; \$SHELL --login"
The question is how can the same thing be achieved for Windows 10 remotes? If nothing else works I would also accept changing the default entry point in git bash for any ssh sessions on the remote.
Please note that I am not looking for help setting up ssh (already works). I just want to jump right into a specific directory when a session is started.
I was able to figure this thing out myself. The following command gets the job done. Using double and single quotes together is required to make it work (in no particular order).
ssh -t user#x.x.x.x "'cd /targetDir ; bash'"

How to Setup VcXSrv for use with WSL2

How do you setup VcXSrv.exe on Windows 10 to work with WSL2 without disabling access control? Every description on the internet shows to disable the access control, but this allows any program on the local network to log your keystrokes and mouse movements among other things.
Rather than disabling access control on VcXSrv, you should use the .Xauthority file to share keys between your X11 clients and the VcXSrv X11 server. The .Xauthority contains a collection of authorization keys indexed by the DISPLAY . You'll need to setup this file with a key for your particular Windows host and share that file between the VcXSrv and your X11 clients running on your WSL2 distro. To setup this, follow these steps:
Run your WSL2 distro (Assuming this is a debian based one) and install xauth, md5sum and gawk or awk. We'll also install some X11 client to test our setup. In this case, we'll install gnome-terminal but you can install something else if you want. On an Ubuntu distro, you can do:
sudo apt install -y xauth coreutils gawk gnome-terminal
xauth list # this should be an empty list
magiccookie=$(echo '{some-pass-phrase}'|tr -d '\n\r'|md5sum|gawk '{print $1}')
xauth add host.docker.internal:0 . $magiccookie
cp ~/.Xauthority /mnt/c/Users/{WindowsUserName}
Add the following to either your ~/.bashrc in your WSL2 distro home dir
export DISPLAY=host.docker.internal:0
We need to create either an XLaunch configuration file (i.e. config.xlaunch ) or
a shortcut to VcXSrv.exe with the desired command line args. XLaunch is a simple launcher
that assists in setting up the arguments and in turn calls vcxsrv.exe. We'll ignore using XLaunch and
just create our own shortcut with the appropriate arguments.
We want to run VcXSrv.exe with these args:
vcxsrv.exe -multiwindow -clipboard -wgl -auth {.XAuthority file} -logfile {A Log file} -logverbose {int log level}
From above, we copied the .Xauthority file to /mnt/c/Users/{WindowsUserName}/.Xauthority which means our desired command line is:
vcxsrv.exe -multiwindow -clipboard -wgl -auth "c:\users\{WindowsUserName}\.Xauthority" -logfile "c:\users\{WindowsUserName}\VcXSrv.log" -logverbose 5
Feel free to omit the logfile and logverbose options if you're not debugging any issues. So you can just do:
vcxsrv.exe -multiwindow -clipboard -wgl -auth "c:\users\{WindowsUserName}\.Xauthority"
Remember to replace {WindowsUserName} with the name of your folder under c:\Users.
To create the shortcut, navigate to where VcXSrv.exe is installed. The default location of this is
C:\Program Files\VcXSrv\VcXSrv.exe
In the explorer file window, right click on the VcXSrv.exe and click "Create Shortcut" . This will create a shortcut
on your desktop.
Right click over the created shortcut icon, and select properties.
In the Shortcut tab, append the arguments above after the executable . It should look something like:
"C:\Program Files\VcXSrv\VcXSrv.exe" -multiwindow -clipboard -wgl -auth "c:\users\{WindowsUserName}\.Xauthority"
In the General tab of the Properties dialog, change the name to be "VcXSrv with XAuthority".
Click ok.
Now you can start the X11 server by double clicking on the shortcut.
If you wish to have the X11 server started at startup, follow the instructions here:
https://support.microsoft.com/en-us/windows/add-an-app-to-run-automatically-at-startup-in-windows-10-150da165-dcd9-7230-517b-cf3c295d89dd
Now back in the WSL distro terminal, you should be able to run
the gnome-terminal or other X11 client and have it display securely
on the VcXSrv X11 server running on the Windows host.
export DISPLAY=host.docker.internal:0
gnome-terminal
This should result in the gnome-terminal being displayed on your X11 Server. Further, the xauthority file will be used to allow only authorized clients to connect to your X11 server.

Running SSH Agent when starting Git Bash on Windows

I am using git bash. I have to use
eval `ssh-agent.exe`
ssh-add /my/ssh/location/
every time when I start a new git bash.
Is there a way to set ssh agent permanently? Or does windows has a good way
to manage the ssh keys?
I'm a new guy, please give me detailed tutorial, thanks!
2013: In a git bash session, you can add a script to ~/.profile or ~/.bashrc (with ~ being usually set to %USERPROFILE%), in order for said session to launch automatically the ssh-agent.
If the file doesn't exist, just create it.
This is what GitHub describes in "Working with SSH key passphrases".
The "Auto-launching ssh-agent on Git for Windows" section of that article has a robust script that checks if the agent is running or not.
Below is just a snippet, see the GitHub article for the full solution.
# This is just a snippet. See the article above.
if ! agent_is_running; then
agent_start
ssh-add
elif ! agent_has_keys; then
ssh-add
fi
Other Resources:
"Getting ssh-agent to work with git run from windows command shell" has a similar script, but I'd refer to the GitHub article above primarily, which is more robust and up to date.
hardsetting adds in the comments (2018):
If you want to enter the passphrase the first time you need it, and not when opening a shell, the cleanest way to me is:
removing the ssh-add from the .bash_profile, and
adding "AddKeysToAgent yes" to your .ssh/config file (see "How to make ssh-agent automatically add the key on demand?").
This way you don't even have to remember running ssh-add.
And Tao adds in the comments (2022):
It's worth noting why this script makes particular sense in Windows, vs (for example) the more standard linuxey script noted by #JigneshGohel in another answer:
By not relying on the SSH_AGENT_PID at all, this script works across different msys & cygwin environments.
An agent can be started in msys2, and still used in git bash, as the SSH_AUTH_SOCK path can be reached in either environment.
The PID from one environment cannot be queried in the other, so a PID-based approach keeps resetting/creating new ssh-agent processes on each switch.
P.S: These instructions are in context of a Bash shell opened in Windows 10 Linux Subsystem and doesn't mention about sym-linking SSH keys generated in Windows with Bash on Ubuntu on Windows
1) Update your .bashrc by adding following in it
# Set up ssh-agent
SSH_ENV="$HOME/.ssh/environment"
function start_agent {
echo "Initializing new SSH agent..."
touch $SSH_ENV
chmod 600 "${SSH_ENV}"
/usr/bin/ssh-agent | sed 's/^echo/#echo/' >> "${SSH_ENV}"
. "${SSH_ENV}" > /dev/null
/usr/bin/ssh-add
}
# Source SSH settings, if applicable
if [ -f "${SSH_ENV}" ]; then
. "${SSH_ENV}" > /dev/null
kill -0 $SSH_AGENT_PID 2>/dev/null || {
start_agent
}
else
start_agent
fi
2) Then run $ source ~/.bashrc to reload your config.
The above steps have been taken from https://github.com/abergs/ubuntuonwindows#2-start-an-bash-ssh-agent-on-launch
3) Create a SSH config file, if not present. Use following command for creating a new one: .ssh$ touch config
4) Add following to ~/.ssh/config
Host github.com-<YOUR_GITHUB_USERNAME>
HostName github.com
User git
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_work_gmail # path to your private key
AddKeysToAgent yes
Host csexperimental.abc.com
IdentityFile ~/.ssh/id_work_gmail # path to your private key
AddKeysToAgent yes
<More hosts and github configs can be added in similar manner mentioned above>
5) Add your key to SSH agent using command $ ssh-add ~/.ssh/id_work_gmail and then you should be able to connect to your github account or remote host using ssh. For e.g. in context of above code examples:
$ ssh github.com-<YOUR_GITHUB_USERNAME>
or
$ ssh <USER>#csexperimental.abc.com
This adding of key to the SSH agent should be required to be performed only one-time.
6) Now logout of your Bash session on Windows Linux Subsystem i.e. exit all the Bash consoles again and start a new console again and try to SSH to your Github Host or other host as configured in SSH config file and it should work without needing any extra steps.
Note:
If you face Bad owner or permissions on ~/.ssh/config then update the permissions using the command chmod 600 ~/.ssh/config. Reference: https://serverfault.com/a/253314/98910
For the above steps to work you will need OpenSSH v 7.2 and newer. If you have older one you can upgrade it using the steps mentioned at https://stackoverflow.com/a/41555393/936494
The same details can be found in the gist Windows 10 Linux Subsystem SSH-agent issues
Thanks.
If the goal is to be able to push to a GitHub repo whenever you want to, then in Windows under C:\Users\tiago\.ssh where the keys are stored (at least in my case), create a file named config and add the following in it
Host github.com
HostName github.com
User your_user_name
IdentityFile ~/.ssh/your_file_name
Then simply open Git Bash and you'll be able to push without having to manually start the ssh-agent and adding the key.
I found the smoothest way to achieve this was using Pageant as the SSH agent and plink.
You need to have a putty session configured for the hostname that is used in your remote.
You will also need plink.exe which can be downloaded from the same site as putty.
And you need Pageant running with your key loaded. I have a shortcut to pageant in my startup folder that loads my SSH key when I log in.
When you install git-scm you can then specify it to use tortoise/plink rather than OpenSSH.
The net effect is you can open git-bash whenever you like and push/pull without being challenged for passphrases.
Same applies with putty and WinSCP sessions when pageant has your key loaded. It makes life a hell of a lot easier (and secure).
I could not get this to work based off the best answer, probably because I'm such a PC noob and missing something obvious. But just FYI in case it helps someone as challenged as me, what has FINALLY worked was through one of the links here (referenced in the answers). This involved simply pasting the following to my .bash_profile:
env=~/.ssh/agent.env
agent_load_env () { test -f "$env" && . "$env" >| /dev/null ; }
agent_start () {
(umask 077; ssh-agent >| "$env")
. "$env" >| /dev/null ; }
agent_load_env
# agent_run_state: 0=agent running w/ key; 1=agent w/o key; 2= agent not running
agent_run_state=$(ssh-add -l >| /dev/null 2>&1; echo $?)
if [ ! "$SSH_AUTH_SOCK" ] || [ $agent_run_state = 2 ]; then
agent_start
ssh-add
elif [ "$SSH_AUTH_SOCK" ] && [ $agent_run_state = 1 ]; then
ssh-add
fi
unset env
I probably have something configured weird, but was not successful when I added it to my .profile or .bashrc. The other real challenge I've run into is I'm not an admin on this computer and can't change the environment variables without getting it approved by IT, so this is a solution for those that can't access that.
You know it's working if you're prompted for your ssh password when you open git bash. Hallelujah something finally worked.
Put this in your ~/.bashrc (or a file that's source'd from it) which will stop it from being run multiple times unnecessarily per shell:
if [ -z "$SSH_AGENT_PID" ]; then
eval `ssh-agent -s`
fi
And then add "AddKeysToAgent yes" to ~/.ssh/config:
Host *
AddKeysToAgent yes
ssh to your server (or git pull) normally and you'll only be asked for password/passphrase once per session.
As I don't like using putty in Windows as a workaround, I created a very simple utility ssh-agent-wrapper. It scans your .ssh folders and adds all your keys to the agent. You simply need to put it into Windows startup folder for it to work.
Assumptions:
ssh-agent in path
shh-add in path (both by choosing the "RED" option when installing git
private keys are in %USERPROFILE%/.ssh folder
private keys names start with id (e.g. id_rsa)
I wrote a script and created a git repository, which solves this issue here: https://github.com/Cazaimi/boot-github-shell-win .
The readme contains instructions on how to set the script up, so that each time you open a new window/tab the private key is added to ssh-agent automatically, and you don't have to worry about this, if you're working with remote git repositories.
Create a new .bashrc file in your ~ directory.
There you can put your commands that you want executed everytime you start the bash
Simple two string solution from this answer:
For sh, bash, etc:
# ~/.profile
if ! pgrep -q -U `whoami` -x 'ssh-agent'; then ssh-agent -s > ~/.ssh-agent.sh; fi
. ~/.ssh-agent.sh
For csh, tcsh, etc:
# ~/.schrc
sh -c 'if ! pgrep -q -U `whoami` -x 'ssh-agent'; then ssh-agent -c > ~/.ssh-agent.tcsh; fi'
eval `cat ~/.ssh-agent.tcsh`

vim + COPY + mac over SSH

I access a sever over ssh on which I run vim for editing files. When I try to yank text from vim into an editor locally on my mac (lion) either with y OR "+y it does not work. I end up with the text I copied last locally. It does work if I just use p within vim alright.
To expand on Ray's answer…
When you are using Vim on a remote server via SSH, everything you do in Vim is done on the remote server. The remote server and the remote Vim that you are running on it have zero practical knowledge of your local computer and its system clipboard.
Because of that, y will never put the yanked text in your local clipboard.
In order to copy a chunk of text from the remote Vim to your local machine's clipboard you have three options:
Select the text with your mouse and hit Cmd+C like in any Mac OS X application.
Obviously, it seems to be the easiest but it has at least three limitations:
It is limited to the current screen. If the text you want to yank is not displayed entirely you won't be able to copy all of it.
It doesn't play well with set mouse=a. With this option, any attempt to select something with the mouse will result in a visual mode selection which can't be copied with Cmd+C. As a workaround, you can use Alt+mouse to select the text without entering visual mode or simply remove this setting from your remote ~/.vimrc.
Line numbers are copied as well.
Put the yanked text in a temporary file, scp it to your local machine and use pbcopy to put it in your system clipboard.
This solution seems to be a little convoluted but it works (and the problem itself is also a little bit convoluted). Over the years I've seen a lot of different implementations ranging from simple one liners to client/server setups. Here is one, feel free to google around for others.
Use X-forwarding to connect your local clipboard to the remote clipboard if available.
Had this problem - log in from OSX over SSH to a linux box and cannot copy text from a file, opened with vim.
My workaround is :set mouse=i
By default mouse is enabled in all modes. When you set it to be enabled only in Insert mode you can scroll around and copy when you are not editing (normal mode) but when you start editing (by hitting the I or Insert key) and enter insert mode the mouse acts as cursor placement and you cannot copy from terminal.
You can set that option in ~/.vimrc
See :help mouse for more information about the values you can set and the modes.
My first answer on stackoverflow, but I feel it's a cool (albeit tiny) trick and it's worth posting. So here's what I do :
cat <filename>
When the text is printed onto the terminal, I select all the text with my mouse (the mouse scroll works since we're on the terminal window). Then copy that text with Cmd+C and paste into my local text editor.
The only flaw with this trick is that it's impractical to use if your files are tens of thousands of lines long since selecting all the lines with your mouse would be a task in itself. But for a file of ~2k lines it works well.
My go-to solution is to edit the file with vim from your local machine via scp.
:e scp://remoteuser#server.tld//path/to/document
This keeps your buffer local and makes it easy to copy to your local clipboard.
The other advantage is that you get to use your local vim setup (.vimrc settings, plugins, etc.)
iTerm2 Shell Utilities come with it2copy which allows copying from a remote server to a client clipboard. Install Shell Utilities on the remote server and make sure you have Applications in terminal may access clipboard checked.
Then, go into visual mode, select the text and execute <,'>:w !it2copy
https://github.com/ojroques/vim-oscyank + iTerm2 + tmux worked in my case, this is my workflow:
ssh into the remote host
open a new tmux session
open vim (or neovim) with https://github.com/ojroques/vim-oscyank already installed and configured as the docs say
Some parts of my .vimrc
Plug 'ojroques/vim-oscyank' " clipboard over ssh through tmux
" yank operation don't need to use the *" register (system clipboard)
set clipboard+=unnamedplus
autocmd TextYankPost * if v:event.operator is 'y' && v:event.regname is '' | OSCYankReg " | endif
Yanking within vi in a terminal to which you ssh'd into copies the lines into vi's internal buffer on the remote machine, not into your Mac's clipboard.
Use your mouse. :)
On MacOS, when SSH from machine A to machine B and using vim in machine B, I add this to my .vimrc in machine B:
nmap yr :call system("ssh $machineA_IP pbcopy", #*)<CR>
That way, in normal mode, if you copy something to * register, then type yr, the content of * register in vim#machine_B is copied to machine A's local clipboard, assuming you have setup Vim correctly with +clipboard and * register
Here's an update on the solution #2 from romainl. It creates and alias of the ssh command and launches the remotecopyserver if it's not running and installs the remotecopy(rclip) in the remote server. In short, you don't have to do anything except paste the code snippet below into your bash_profile.
######################## For SSH Remote Copy #########################
export LC_SETUP_RC='command -v rclip >/dev/null 2>&1 || { echo "executing"; mkdir -p /usr/local/bin; if [ ! -f /usr/local/bin/rclip ];then wget https://raw.githubusercontent.com/justone/remotecopy/master/remotecopy -P /usr/local/bin/; ln -s /usr/local/bin/remotecopy /usr/local/bin/rclip; chmod +x /usr/local/bin/remotecopy; fi; if [[ \":\$PATH:\" == *\"/usr/local/bin:\"* ]]; then export PATH=/usr/local/bin:$PATH; fi } > /var/log/rclip.log 2>&1 || echo "Some error occured in setting up rclip. check /var/log/rclip.log"'
ssh_function() {
count="`ps -eaf | grep remotecopyserver | grep -v grep | wc -l`";
if [ "$count" -eq "0" ]; then
mkdir -p $HOME/bin;
if [ ! -f $HOME/bin/remotecopyserver ]; then
wget https://raw.githubusercontent.com/justone/remotecopy/master/remotecopyserver -P $HOME/bin;
chmod +x $HOME/bin/remotecopyserver;
fi;
nohup $HOME/bin/remotecopyserver &
fi;
ssh_cmd=`which ssh`
PARAMS=""
for PARAM in "$#"
do
PARAMS="${PARAMS} \"${PARAM}\""
done
bash -c "ssh ${PARAMS} -R 12345:localhost:12345 -t 'echo \$LC_SETUP_RC | sudo bash; bash -l'"
}
alias ssho=`which ssh`
alias ssh=ssh_function
alias ssh2=ssh_function
vssh_function() {
ssh_config=`vagrant ssh-config`;
if [ "$?" -eq "1" ]; then
echo "Problem with Vagrant config. run 'vagrant ssh-config' to debug"
return 1
fi
PORT=`echo "$ssh_config" | grep Port | grep -o "[0-9]\+"`;
ID_FILE=`echo "$ssh_config" | grep IdentityFile | awk '{print $2}'`
ssh2 -q -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -o PasswordAuthentication=no -i $ID_FILE vagrant#localhost -p $PORT "$#"
}
alias vssh=vssh_function
Once the alias is activated, you can normally use ssh and whenever you need to copy to local clipboard from vim, use
:w !rclip
to copy the whole file to clipboard
:'<,'> !rclip
to copy selected lines from visual mode. You have to press "Cmd+V" or "Ctrl+V" whenever it asks for the secret key.
Bonus
For those who work on Vagrant, there's a wrapper vssh which will execute vagrant ssh but also launches and install the necessary components.
Reference
Latest code snippet here - https://gist.github.com/ningsuhen/7933b206b92fc57364b2
http://endot.org/2011/12/04/remotecopy-copy-from-remote-terminals-into-your-local-clipboard/
https://github.com/justone/remotecopy
Caveats
The alias wraps the ssh command and there might be some unexpected issues. ssho is available if you need to execute ssh without the whole remotecopyserver thing. Alternatively, you can use the alias ssh2 and keep the ssh command as it is.
One trick which i use often during copying vim text using mouse if number of lines get little over-flown my screen is to minimize (Cmd + '-') the text. :) Minimize so much that you can not see by eyes but you can copy all the text in one go.
Instructions for mac + ssh + iterm2 + neovim:
Ssh to your server.
Install iterm shell integration.
Add ~/.iterm2 to the $PATH variable.
Create a ttyup command in e.g. ~/.local/bin.
Add ~/.local/bin to $PATH, if it's not already.
Add the g:clipboard declaration to your init.vim.
ttyup:
#!/bin/bash
# #medgar's ttyup script for passing the output to the parent shell
parent() { awk '{print $4}' "/proc/$1/stat"; }
leader() { awk '{print $6}' "/proc/$1/stat"; }
it2copy > "/proc/$(parent $(leader $$))/fd/0"
init.vim:
let g:clipboard = {
\ 'name': 'myClipboard',
\ 'copy': {
\ '+': ['ttyup'],
\ '*': ['ttyup'],
\ },
\ 'paste': {
\ '+': '+',
\ '*': '*',
\ },
\ 'cache_enabled': 0,
\ }
Or, from the terminal, write less [filename] to get it written to the terminal. Then start by selecting with your mouse, while you hold down-arrow-key down. Then you can select the whole bunch.
I was hoping to improve on my solution here, but instead will share it as it seems on par with some of the others.
When using iTerm2 on a Mac, sshing into machines, running tmux, and then editing with Vim, I have a vertical split iTerm2 window on the Mac that I pull all the way off to the side to make it as skinny as possible.
Then when I want to copy text from Vim, I will click into the tiny slice of iTerm2 window, and go back over and highlight and then copy the text from Vim. This works the best for single lines of text.
If there is a tmux vertical split, highlighting multiple lines in the Vim buffer won't wrap properly, and will copy text from the other tmux window, but otherwise this is great for copying 90% of what I need, without having to exit Vim, cat a file, or do something else.
I also have ample horizontal window space, making the small iTerm2 window not a space hog.
Just use MobaXterm.
I tried lots of ways and none of them is easy. So the only solution I could find is using
MobaXterm. You can see all of the files and open them any way you want.
The easiest way to copy to local machine is via selecting with mouse and then CMD + c to copy. As is noted in another answer this has a few limitations/drawbacks. Consequently, I sought out the alternatives, but after trying for hours (unsuccessfully) to get X11 forwarding working, I instead came up with the following simple workaround (at least for the line-numbering caveat) for aid in mouse copying.
Add the following to your .vimrc to easily toggle line numbers for mouse copying:
nnoremap L :set invnumber <CR>
You can easily change the L to any key of your choice that you wish to be the shortcut key.
#andrewgazelka had a great solution
I don't have it2copy script: https://github.com/gnachman/iTerm2-shell-integration/blob/main/utilities/it2copy
Here is the code I downloaded from :)
Hope someone will feel it is helpful :)
I moved it2copy in my /usr/bin directory for both my server and macbook
Try the other clipboard register - "*y.

Opening a remote file with TextWrangler

My current solution for editing files on a remote web server is to use Fetch to browse the remote machine and TextWrangler to make the edits. But since I'm getting more comfortable navigating the command line on the remote machine (but not comfortable enough to use VIM...), I'd like to be able to type something like 'open filename.txt' on the remote machine and have TextWrangler open up on my local machine. I've heard the term "reverse tunneling" tossed around as an option, but I have no idea what to do next. Any suggestions are greatly appreciated - thanks!
Personally, I use Cyberduck as my S/FTP browser. In Cyberduck's preferences, you can define a default text editor to edit remote files. Now I can just hit Cmd+K when I have a file selected, and it will open up in TextWrangler. Whenever I save, the changes are automatically transferred to the remote file.
I was actually looking to do the same thing, and no one had written it up, so I figured this out today.
There's 2 required and 3 optional parts to this:
Enable ssh login on both computers (required)
Set up an ssh tunnel from the remote machine to your machine (required)
Set up an alias for the ssh tunnel (optional)
Set up an alias for TextWrangler on the remote machine (optional)
Set up ssh keys so you don't have to enter your password every time (optional)
You need to be able to ssh from local to remote to run the commands, and you need to be able to ssh from remote to local so it can send commands to TextWrangler.
To set up the ssh tunnel, you need to run a command on your local machine like:
ssh -f -N -R 10022:localhost:22 [username on remote machine]#[remote machine hostname]
The -f and -N flags put ssh into the background and leave you on your machine. The -R flag binds a port on the remote computer to a port on your local computer. Anything contacting the remote machine on port 10022 will be sent to port 22 on your local computer. The remote port can be anything you want, but you should choose a port > 1024 to avoid conflicts and so you don't have to be root. I chose 10022 because it's similar to ssh's default port of 22. Replace the brackets with your username and machine name.
You'll need to run that once after you log in. To make the command easier on yourself, you can add an alias in your bash profile. Add the following to your local ~/.bash_profile:
alias open-tunnel='ssh -f -N -R 10022:localhost:22 [username on remote machine]#[remote machine hostname]'
Of course, you can choose whatever alias name you like.
Once you've set up the tunnel, you can use a command like this on the remote machine:
ssh -p 10022 [username on local machine]#localhost "edit sftp://[username on remote machine]#[remote machine hostname]//absolute/path/to/file.txt"
The -p flag says to use port 10022 (or whichever port you chose earlier). This will cause the remote machine to connect to your local machine and execute the command in the double quotes without opening an interactive ssh session. The command in the quotes is the command you would run on your local machine to open the remote file in TextWrangler.
To make the command easier on yourself, you can add a function in your bash profile. Add the following to your remote ~/.bash_profile:
function edit { if [[ ${1:0:1} = "/" ]]; then abs_path="$1"; else abs_path="`pwd`/$1"; fi; ssh -p 10022 [username on local machine]#localhost "edit sftp://[username on remote machine]#[remote machine hostname]/$abs_path"; }
This is assuming that you don't have the TextWrangler command line tools installed on the remote machine. If you do, you should name the function something other than edit. For example, tw. Here, ${1:0:1} looks at the first character of the first parameter of the function, which should be the file path. If it doesn't begin with /, we figure out the absolute path by adding the current working directory (pwd) to the beginning. Now, if you're on the remote machine in /home/jdoe/some/directory/ and you run edit some/other/directory/file.txt, the following will be executed on your local machine:
edit sftp://[username on remote machine]#[remote machine hostname]//home/jdoe/some/directory/some/other/directory/file.txt
Lastly, you should set up ssh keys in both directions so you're not prompted for a password every single time. Here's a guide someone else wrote: http://pkeck.myweb.uga.edu/ssh/
I dont think this will allow opening from the command-line, but
Eclipse with Remote-System-Explorer also supports editing of files via ssh connection
I think what you're referring to is called "X11 forwarding" over ssh. Take a look at the ssh_config(5) manpage for configuration (or just use 'ssh' with the '-X' parameter). As far as i know, this does only work with X11 programs (gvim, xemacs, etc.), because the editor is actually running on the host you're connecting to - only the display stuff happens on your local machine. So TextWrangler is not an option, because it's not an X11 program.
I use Interarchy (from nolobe) for remote editing. It's a fairly advanced ftp/sftp client that gives you a finder-style view of your remote files and allows you to use your favourite editor to work on those files.
If you don't like to pay for such a program, there's an Open-Source program called "Fugu" available from the Univerity of Michigan which you can also use.
FileZilla offers this functionality as well. You can download it here. Once you've connected to your sftp you can right-click on the text file and open it with the text editor of your choice.
Minimal answer
You can use Applescript. So from the command line execute this:
osascript <<EOF
tell application "TextWrangler"
activate
open location {"sftp://myusername:#my.server:22222//home/username/.bashrc"}
end tell
EOF
Notes
Obviously you wouldn't want to type a here document on every invocation, so my suggestion would be to put this logic inside a regular shell script:
osascript <<EOF
tell application "TextWrangler"
activate
open location {"$1"}
end tell
EOF
Then invoke the script like this:
sh ~/bin/textwrangler.sh "sftp://myusername:#my.server:22222//home/username/.bashrc"
Specifying a host-qualified path can get tedious each time so either hardcode that in your script, or bind the script invocation to a keystroke via your shell. For bash:
bind '"\et":"sh ~/bin/textwrangler.sh \"sftp://myusername:#my.server:22222/\""'
Now you generate the majority of the command by pressing Alt-t

Resources