Use an ssh port forward with a backgrounded commandless ssh session:
$ ssh -N -f -L 5433:localhost:5432 remoteserver
with which you can then use:
$ psql -h localhost -p 5433
psql commands like
\i, etc will refer to files on the local computer.
If you're trying to do this for scripting purposes then you probably want to use ssh's
-n option and a passwordless ssh key with options set in
authorized_keys to prevent a shell from being spawned so all you can do is port forward a given port. This is very important for security when using passwordless keys.
ssh-agent provides a somewhat more secure alternative but it's clumsier for scripting. Remember that your script will need to record the process ID of the background ssh session it spawned and kill it at the end of the task. It's sometimes easier to use shell job control rather than ssh's own daemonize mode; that way the shell keeps track of the process backgrounded with
& and it can be terminated with
kill %jobid. See bash job control. (You need to background the port forwarding ssh session so that execution of the script can continue and run
For interactive use you can just invoke the remote
ssh, in which case commands like
\copy, etc will refer to files local to the server you ssh'd to, not your local computer:
$ ssh remoteserver psql
This works for scripting purposes too, but is somewhat less secure than doing port forwarding since
psql is a pretty powerful program that lets you read and write arbitrary files, spawn a shell, etc. You can't really limit what a passwordless ssh key can do if it's allowed to remotely invoke
psql. On the other hand, it's a lot simpler to write:
ssh remoteserver psql <<'__END__'
INSERT INTO blah(a,b,c) VALUES (1,2,3);
UPDATE otherblah SET x = 99, y = 912;
than to muck about with background ssh sessions. Really it depends on what your priorities are.