output
stringlengths
9
26.3k
input
stringlengths
26
29.8k
instruction
stringlengths
14
159
On the server, in .profile or whatever is run when you log in: if [ -n "$USE_DIR_A" ]; then cd dir_a elif [ -n "$USE_DIR_B" ]; then cd dir_b fiThen, on the local machine, set both variables: export USE_DIR_A=yes export USE_DIR_B=yesand, set your .ssh/config like this: Host env1 User me Port 2222 # here directory should be /srv/project/env1 SendEnv USE_DIR_A HostName 172.16.16.2Host env2_test User me Port 2222 # here directory should be /srv/project/env2_test SendEnv USE_DIR_B HostName 172.16.16.2Of course, you could just have one ssh config that sends one variable, and set that variable to the directory you want for each machine, but that's not what you asked for. Beware SSH connection sharing though: it can affect which scripts are run on start-up in subsequent connections.
Is there any way to force ssh to change it's working dir in ~/.ssh/config or by using other configuration files? I have a lot of servers with different environments. Each environment is installed in a specific directory and it would be really helpful to be in this specific directory right after login. Unfortunately, sometimes several environments can be hosted on the same server. That's why I need to make it config based, as currently I have a separate entry in config for each env. Example: Host env1 User me Port 2222 # here directory should be /srv/project/env1 HostName 172.16.16.2Host env2_test User me Port 2222 # here directory should be /srv/project/env2_test HostName 172.16.16.2Host env54 User me Port 2225 # here directory should be /srv/project/env54 HostName 172.16.16.3I can do it with ssh -t env54 'cd /srv/project/env54 ; bash', but it's annoying to retype it each time or even put it in an alias. I believe the *nix way is to handle it via configuration.
force ssh to change dir after login based on config
I figured out working syntax, I can connect directly to the gcloud compute instance using the name by adding to my ssh config: Host gcloud User me ProxyCommand gcloud compute --project "myproject" ssh --zone "myzone" me@gcloud --command="nc 0.0.0.0 22"Now I can say ssh gcloud To use it as a jumpbox I can add to my config Host *.gc User me IdentityFile myIdentityFile ProxyCommand gcloud compute --project "myproject" ssh --zone "myzone" me@gcloud --command="nc $(basename %h .gc) %p"This allows me to run ssh <instance_ip>.gc using the gcloud compute instance as a jumpbox.
I would like to use my ssh config to use a google cloud compute instance as a jumpbox to connect to another box. However, I am having problems getting a config that will allow me to even connect to the google cloud compute instance. The desired functionality is ssh gcloud would connect me to the gcloud instance. ssh foo connects me to a node that I can only connect to through the gcloud box. To connect to gcloud I can run: /home/me/google-cloud-sdk/bin/gcloud compute --project "myproject" ssh --zone "myzone" me@gcloudSo I added an entry to my .ssh/config: Host gcloud ProxyCommand /home/me/google-cloud-sdk/bin/gcloud compute --project "myproject" ssh --zone "myzone" me@gcloudI then run ssh gcloud and get: # ssh gcloud Pseudo-terminal will not be allocated because stdin is not a terminal. -bash: line 1: $'SSH-2.0-OpenSSH_8.0\r': command not foundIt seems to establish a connection, but I don't have a prompt to type at, so I press ctrl-c to kill it.Debugging I tried /home/me/google-cloud-sdk/bin/gcloud compute --project "myproject" ssh --zone "myzone" me@gcloud --dryrunThis shows the ssh command that is run, it adds on a lot of flags I don't really care to have, adding the --plain flag gives me a stripped down version, with one -t flag. # /home/me/google-cloud-sdk/bin/gcloud compute --project "myproject" ssh --zone "myzone" me@gcloud /usr/bin/ssh -t me@<gcloud_ip>Without adding --dryrun I can connect with the --plain flag, but not when I use it in my ssh config. Arguments after -- are passed to ssh. This led me to try adding -- -t which once again connects, this time no warning is provided and no prompt. I've also tried -- -tt which gives the error and no prompt. By adding -- -vvv I can get more verbose logs, here they are: $ ssh gcloud OpenSSH_8.0p1, OpenSSL 1.1.1d FIPS 10 Sep 2019 debug1: Reading configuration data /home/me/.ssh/config debug1: Reading configuration data /etc/ssh/ssh_config debug3: /etc/ssh/ssh_config line 51: Including file /etc/ssh/ssh_config.d/05-redhat.conf depth 0 debug1: Reading configuration data /etc/ssh/ssh_config.d/05-redhat.conf debug2: checking match for 'final all' host <gcloud_ip> originally <gcloud_ip> debug3: /etc/ssh/ssh_config.d/05-redhat.conf line 3: not matched 'final' debug2: match not found debug3: /etc/ssh/ssh_config.d/05-redhat.conf line 5: Including file /etc/crypto-policies/back-ends/openssh.config depth 1 (parse only) debug1: Reading configuration data /etc/crypto-policies/back-ends/openssh.config debug3: gss kex names ok: [gss-gex-sha1-,gss-group14-sha1-,gss-group1-sha1-] debug3: kex names ok: [curve25519-sha256,[emailprotected],ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1] debug1: configuration requests final Match pass debug2: resolve_canonicalize: hostname <gcloud_ip> is address debug1: re-parsing configuration debug1: Reading configuration data /home/me/.ssh/config debug1: Reading configuration data /etc/ssh/ssh_config debug3: /etc/ssh/ssh_config line 51: Including file /etc/ssh/ssh_config.d/05-redhat.conf depth 0 debug1: Reading configuration data /etc/ssh/ssh_config.d/05-redhat.conf debug2: checking match for 'final all' host <gcloud_ip> originally <gcloud_ip> debug3: /etc/ssh/ssh_config.d/05-redhat.conf line 3: matched 'final' debug2: match found debug3: /etc/ssh/ssh_config.d/05-redhat.conf line 5: Including file /etc/crypto-policies/back-ends/openssh.config depth 1 debug1: Reading configuration data /etc/crypto-policies/back-ends/openssh.config debug3: gss kex names ok: [gss-gex-sha1-,gss-group14-sha1-,gss-group1-sha1-] debug3: kex names ok: [curve25519-sha256,[emailprotected],ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1] Pseudo-terminal will not be allocated because stdin is not a terminal. debug2: ssh_connect_direct debug1: Connecting to <gcloud_ip> [<gcloud_ip>] port 22. debug1: Connection established. debug1: identity file /home/me/.ssh/google_compute_engine type 0 debug1: identity file /home/me/.ssh/google_compute_engine-cert type -1 debug1: Local version string SSH-2.0-OpenSSH_8.0 debug1: Remote protocol version 2.0, remote software version OpenSSH_7.4p1 Debian-10+deb9u7 debug1: match: OpenSSH_7.4p1 Debian-10+deb9u7 pat OpenSSH_7.0*,OpenSSH_7.1*,OpenSSH_7.2*,OpenSSH_7.3*,OpenSSH_7.4*,OpenSSH_7.5*,OpenSSH_7.6*,OpenSSH_7.7* compat 0x04000002 debug2: fd 4 setting O_NONBLOCK debug1: Authenticating to <gcloud_ip>:22 as 'metrics' debug3: send packet: type 20 debug1: SSH2_MSG_KEXINIT sent debug3: receive packet: type 20 debug1: SSH2_MSG_KEXINIT received debug2: local client KEXINIT proposal debug2: KEX algorithms: curve25519-sha256,[emailprotected],ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1,ext-info-c debug2: host key algorithms: [emailprotected],[emailprotected],[emailprotected],[emailprotected],[emailprotected],[emailprotected],[emailprotected],ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-ed25519,rsa-sha2-512,rsa-sha2-256,ssh-rsa,ssh-dss debug2: ciphers ctos: [emailprotected],[emailprotected],aes256-ctr,aes256-cbc,[emailprotected],aes128-ctr,aes128-cbc debug2: ciphers stoc: [emailprotected],[emailprotected],aes256-ctr,aes256-cbc,[emailprotected],aes128-ctr,aes128-cbc debug2: MACs ctos: [emailprotected],[emailprotected],[emailprotected],[emailprotected],hmac-sha2-256,hmac-sha1,[emailprotected],hmac-sha2-512 debug2: MACs stoc: [emailprotected],[emailprotected],[emailprotected],[emailprotected],hmac-sha2-256,hmac-sha1,[emailprotected],hmac-sha2-512 debug2: compression ctos: none,[emailprotected],zlib debug2: compression stoc: none,[emailprotected],zlib debug2: languages ctos: debug2: languages stoc: debug2: first_kex_follows 0 debug2: reserved 0 debug2: peer server KEXINIT proposal debug2: KEX algorithms: curve25519-sha256,[emailprotected],ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group14-sha256,diffie-hellman-group14-sha1 debug2: host key algorithms: ssh-rsa,rsa-sha2-512,rsa-sha2-256,ecdsa-sha2-nistp256,ssh-ed25519 debug2: ciphers ctos: [emailprotected],aes128-ctr,aes192-ctr,aes256-ctr,[emailprotected],[emailprotected] debug2: ciphers stoc: [emailprotected],aes128-ctr,aes192-ctr,aes256-ctr,[emailprotected],[emailprotected] debug2: MACs ctos: [emailprotected],[emailprotected],[emailprotected],[emailprotected],[emailprotected],[emailprotected],[emailprotected],hmac-sha2-256,hmac-sha2-512,hmac-sha1 debug2: MACs stoc: [emailprotected],[emailprotected],[emailprotected],[emailprotected],[emailprotected],[emailprotected],[emailprotected],hmac-sha2-256,hmac-sha2-512,hmac-sha1 debug2: compression ctos: none,[emailprotected] debug2: compression stoc: none,[emailprotected] debug2: languages ctos: debug2: languages stoc: debug2: first_kex_follows 0 debug2: reserved 0 debug1: kex: algorithm: curve25519-sha256 debug1: kex: host key algorithm: ecdsa-sha2-nistp256 debug1: kex: server->client cipher: [emailprotected] MAC: <implicit> compression: none debug1: kex: client->server cipher: [emailprotected] MAC: <implicit> compression: none debug1: kex: curve25519-sha256 need=32 dh_need=32 debug1: kex: curve25519-sha256 need=32 dh_need=32 debug3: send packet: type 30 debug1: expecting SSH2_MSG_KEX_ECDH_REPLY debug3: receive packet: type 31 debug1: Server host key: ecdsa-sha2-nistp256 SHA256:SSiahqZ80hKyZnrwU7tXf7yVH4iw0T1VuGa273/rSm8 debug1: using hostkeyalias: compute.6046273207033681025 debug3: hostkeys_foreach: reading file "/home/me/.ssh/google_compute_known_hosts" debug3: record_hostkey: found key type ECDSA in file /home/me/.ssh/google_compute_known_hosts:164 debug3: load_hostkeys: loaded 1 keys from compute.6046273207033681025 debug1: Host 'compute.6046273207033681025' is known and matches the ECDSA host key. debug1: Found key in /home/me/.ssh/google_compute_known_hosts:164 debug3: send packet: type 21 debug2: set_newkeys: mode 1 debug1: rekey out after 4294967296 blocks debug1: SSH2_MSG_NEWKEYS sent debug1: expecting SSH2_MSG_NEWKEYS debug3: receive packet: type 21 debug1: SSH2_MSG_NEWKEYS received debug2: set_newkeys: mode 0 debug1: rekey in after 4294967296 blocks debug1: Will attempt key: /home/me/.ssh/google_compute_engine RSA SHA256:v+I+Ar49s9xNTLoC6jSGYwsSeYhHtnCw7B2JWDF8UWs explicit agent debug2: pubkey_prepare: done debug3: send packet: type 5 debug3: receive packet: type 7 debug1: SSH2_MSG_EXT_INFO received debug1: kex_input_ext_info: server-sig-algs=<ssh-ed25519,ssh-rsa,ssh-dss,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521> debug3: receive packet: type 6 debug2: service_accept: ssh-userauth debug1: SSH2_MSG_SERVICE_ACCEPT received debug3: send packet: type 50 debug3: receive packet: type 51 debug1: Authentications that can continue: publickey debug3: start over, passed a different list publickey debug3: preferred gssapi-with-mic,publickey,keyboard-interactive,password debug3: authmethod_lookup publickey debug3: remaining preferred: keyboard-interactive,password debug3: authmethod_is_enabled publickey debug1: Next authentication method: publickey debug1: Offering public key: /home/me/.ssh/google_compute_engine RSA SHA256:v+I+Ar49s9xNTLoC6jSGYwsSeYhHtnCw7B2JWDF8UWs explicit agent debug3: send packet: type 50 debug2: we sent a publickey packet, wait for reply debug3: receive packet: type 60 debug1: Server accepts key: /home/me/.ssh/google_compute_engine RSA SHA256:v+I+Ar49s9xNTLoC6jSGYwsSeYhHtnCw7B2JWDF8UWs explicit agent debug3: sign_and_send_pubkey: RSA SHA256:v+I+Ar49s9xNTLoC6jSGYwsSeYhHtnCw7B2JWDF8UWs debug3: sign_and_send_pubkey: signing using ssh-rsa debug3: send packet: type 50 debug3: receive packet: type 52 debug1: Authentication succeeded (publickey). Authenticated to <gcloud_ip> ([<gcloud_ip>]:22). debug2: fd 5 setting O_NONBLOCK debug2: fd 7 setting O_NONBLOCK debug1: channel 0: new [client-session] debug3: ssh_session2_open: channel_new: 0 debug2: channel 0: send open debug3: send packet: type 90 debug1: Requesting [emailprotected] debug3: send packet: type 80 debug1: Entering interactive session. debug1: pledge: network debug2: client_check_window_change: changed debug3: receive packet: type 80 debug1: client_input_global_request: rtype [emailprotected] want_reply 0 debug3: receive packet: type 91 debug2: channel_input_open_confirmation: channel 0: callback start debug2: fd 4 setting TCP_NODELAY debug3: ssh_packet_set_tos: set IP_TOS 0x20 debug2: client_session2_setup: id 0 debug1: Sending environment. debug1: Sending env XMODIFIERS = @im=ibus debug2: channel 0: request env confirm 0 debug3: send packet: type 98 debug1: Sending env LANG = en_US.UTF-8 debug2: channel 0: request env confirm 0 debug3: send packet: type 98 debug2: channel 0: request shell confirm 1 debug3: send packet: type 98 debug2: channel_input_open_confirmation: channel 0: callback done debug2: channel 0: open confirm rwindow 0 rmax 32768 debug2: channel 0: rcvd adjust 2097152 debug3: receive packet: type 99 debug2: channel_input_status_confirm: type 99 id 0 debug2: shell request accepted on channel 0 debug2: channel 0: rcvd ext data 59 -bash: line 1: $'SSH-2.0-OpenSSH_8.0\r': command not found debug2: channel 0: written 59 to efd 8As for jumping (my longer-term goal), I can connect to the node with: ssh -J me@<gcloud_ip> -p <port> me@<node_ip>but I would like to encapsulate this in my config so I can say ssh node.
ssh config to start session with google cloud compute instance
When you write $PGWA without quotes, this splits the value of PGWA at whitespace¹. Quote characters have no special meaning there, so you end up with the words -o, ProxyCommand="ssh, gateway1, nc, %h and %p". See Why does my shell script choke on whitespace or other special characters? for more explanations. A variable expansion outside of double quotes is almost always a mistake. It's always a mistake unless you know why you need to leave the double quotes off. What you need to do is to pass two arguments to the SSH command: -o and ProxyCommand=ssh gateway2 nc --proxy %h %p --proxy-type socks4. In zsh, you could just set PGWA to an array: PGWA=(-o 'ProxyCommand=ssh gateway2 nc --proxy %h %p --proxy-type socks4') ssh $PGWA …In other shells such as bash and ksh, this requires more typing, because of their design misfeature that unquoted variable expansions undergo splitting and because of their explicit syntax for arrays: PGWA=(-o 'ProxyCommand=ssh gateway2 nc --proxy %h %p --proxy-type socks4') ssh "${PGWA[@]}" …A method that would work in any sh-like shell and wouldn't require much typing would be to define functions. pgwa () { typeset c="$1"; shift "$c" -o 'ProxyCommand=ssh gateway2 nc --proxy %h %p --proxy-type socks4' "$@" } pgwa ssh …But I think the best solution would be to put all of these definitions in your .ssh/config where they belong. This way you wouldn't need any shell tricks and the configurations would work in other programs (rsync, sshfs, GUI file transfer programs, etc.). If you add a new VM behind gateway1, either add an entry to .ssh/config or use ssh -o HostName=new-vm something-behind-gateway1 … ¹ Plus other things that don't matter here.
I have a bunch of Linux machines behind 2 gateways. To connect to set one I do ssh -o ProxyCommand="ssh gateway1 nc %h %p" machines_behind_1 ssh -o ProxyCommand="ssh gateway2 nc --proxy %h %p --proxy-type socks4" machines_behind_2To simplify this process, I thought I would create a environment variable to hold the proxycommand and simply use that. So I did export PGWA='-o ProxyCommand="ssh gateway1 nc %h %p"' export PGWB='-o ProxyCommand="ssh gateway2 nc --proxy %h %p --proxy-type socks4"'Then, depending on the machine I want to connect, I would do ssh $PGWA machine_behind_1 ssh $PGWB machine_behind_2 But I get this error - /bin/bash: -c: line 0: unexpected EOF while looking for matching `"' /bin/bash: -c: line 1: syntax error: unexpected end of fileAny idea why? I can't use any ssh_config tricks, because I don't know the hostnames ahead of time. I might create a new VM behind gateway1 , and I will need to use the first proxy command. The only thing I can think of is create a new alias, a function or a shell script which basically does ssh -o foo $@ and use that instead. But then, I need to remember to create an alias/shell script or function for scp as well, which too I use regularly. I would rather be able to do it automatically. I kinda hoped I could do something like ssh gw1-host and do some manipulation inside the config file to convert it to ssh -o foo host through the first gateway, but that kind of regex manipulation is not allowed inside the ssh_config. Any way I can achieve what I want without individual ssh / scp alias/script/function? EDIT: I had made a mistake with the quoting when I copy-pasted the environment variable into stack exchange here.
Syntax error with variable containing quotes
You're actually using myEC2 as a jump host. You could ssh to node1 from your laptop with: ssh -p 3000 -J ubuntu@myEC2 xavier@localhostThe corresponding ssh_config entries would look like: Host node1 Hostname localhost User xavier Port 3000 IdentityFile key.pem ProxyJump ubuntu@myEC2Note that the IdentityFile there is the one used for authenticating to node1. To specify one for myEC2, you'd use another Host entry for myEC2.
I set up a reverse SSH tunnel to access a node, node1, behind a NAT. I have set up an EC2 instance, myEC2, to act as the intermediary. From my laptop, when I want to access node1, I have to SSH into the EC2 in order to then SSH into the node. The workflow is like this:In node1, make sure to run: ssh -i key.pem -R 3000:localhost:22 ubuntu@myEC2. This is always running in a service. From my laptop, SSH into the EC2: ssh ubuntu@myEC2 Once inside the EC2: ssh xavier@localhost -p 3000 I'm in node1!What I'm looking for is a way of expressing that workflow in a SSH config that I can use to login directly into node1 from my laptop. This will help me access node1 via Visual Studio Code's Remote SSH extension. I tried something like this: Host node1 Hostname myEC2 User ubuntu Port 3000 IdentityFile key.pemBut that does not work, I assume it is because Port should be 22 rather than 3000. I just really don't know how to express the workflow. I have looked into ProxyJump but I'm not sure if that is what I'm looking for and to be honest I haven't had success with that either. Any suggestions are welcomed! =DEdit #1: After following Stéphane's suggestions I ended up with an ssh_config file that looks like this: Host myEC2 Hostname <myEC2_IP> User ubuntu Port 22 IdentityFile ec2_key.pemHost node1 Hostname localhost User xavier Port 3000 IdentityFile /path/to/node1-id_rsa ProxyJump ubuntu@myEC2While I can SSH into myEC2 with no issues, I can't go into node1. My understanding is that this is supposed to be equivalent to ssh -p 3000 -J ubuntu@myEC2 xavier@localhost. Any help is greatly appreciated! This is what I get by adding the -v flag to SSH. xaviermerino@Xaviers-MBP .ssh % ssh doc debug1: Executing proxy command: exec ssh -l ubuntu -W '[localhost]:3000' myEC2 debug1: identity file node1-id_rsa type -1 debug1: identity file node1-id_rsa-cert type -1 debug1: Local version string SSH-2.0-OpenSSH_8.1 debug1: Connecting to myEC2 [myEC2_IP_ADDRESS] port 22. debug1: Connection established. debug1: identity file ec2_key.pem type -1 debug1: identity file ec2_key.pem-cert type -1 debug1: Local version string SSH-2.0-OpenSSH_8.1 debug1: Remote protocol version 2.0, remote software version OpenSSH_8.2p1 Ubuntu-4ubuntu0.2 debug1: match: OpenSSH_8.2p1 Ubuntu-4ubuntu0.2 pat OpenSSH* compat 0x04000000 debug1: Authenticating to myEC2_IP_ADDRESS:22 as 'ubuntu' debug1: SSH2_MSG_KEXINIT sent debug1: SSH2_MSG_KEXINIT received debug1: kex: algorithm: curve25519-sha256 debug1: kex: host key algorithm: ecdsa-sha2-nistp256 debug1: kex: server->client cipher: [emailprotected] MAC: <implicit> compression: none debug1: kex: client->server cipher: [emailprotected] MAC: <implicit> compression: none debug1: expecting SSH2_MSG_KEX_ECDH_REPLY debug1: Server host key: ecdsa-sha2-nistp256 SHA256:/U4HE+zUBFNZJgxDM6lWDW7FX8GSHXWYc/fMEyOvMlw debug1: Host 'myEC2_IP_ADDRESS' is known and matches the ECDSA host key. debug1: Found key in /Users/xaviermerino/.ssh/known_hosts:226 debug1: rekey out after 134217728 blocks debug1: SSH2_MSG_NEWKEYS sent debug1: expecting SSH2_MSG_NEWKEYS debug1: SSH2_MSG_NEWKEYS received debug1: rekey in after 134217728 blocks debug1: Will attempt key: ec2_key.pem explicit debug1: SSH2_MSG_EXT_INFO received debug1: kex_input_ext_info: server-sig-algs=<ssh-ed25519,[emailprotected],ssh-rsa,rsa-sha2-256,rsa-sha2-512,ssh-dss,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,[emailprotected]> debug1: SSH2_MSG_SERVICE_ACCEPT received debug1: Authentications that can continue: publickey debug1: Next authentication method: publickey debug1: Trying private key: ec2_key.pem debug1: Authentication succeeded (publickey). Authenticated to myEC2 ([IP_Address_Goes_Here]:22). debug1: channel_connect_stdio_fwd localhost:3000 debug1: channel 0: new [stdio-forward] debug1: getpeername failed: Bad file descriptor debug1: Requesting [emailprotected] debug1: Entering interactive session. debug1: pledge: network debug1: client_input_global_request: rtype [emailprotected] want_reply 0 debug1: Remote: /home/ubuntu/.ssh/authorized_keys:1: key options: agent-forwarding port-forwarding pty user-rc x11-forwarding channel 0: open failed: connect failed: Connection refused stdio forwarding failed kex_exchange_identification: Connection closed by remote hostI'm not sure what this means Does it have to do with the settings at sshd_config in the EC2?. This is what I have in there: #AllowAgentForwarding yes #AllowTcpForwarding yes GatewayPorts yes X11Forwarding yes #X11DisplayOffset 10 #X11UseLocalhost yes #PermitTTY yes PrintMotd no #PrintLastLog yes #TCPKeepAlive yes #PermitUserEnvironment no #Compression delayed #ClientAliveInterval 0 #ClientAliveCountMax 3 #UseDNS no #PidFile /var/run/sshd.pid #MaxStartups 10:30:100 #PermitTunnel no #ChrootDirectory none #VersionAddendum noneEdit #2: Someone had turned off the computers. It now works! To summarize it for whoever is looking into this. To solve this, I needed: Host myEC2 Hostname <myEC2_IP> User ubuntu Port 22 IdentityFile ec2_key.pemHost node1 Hostname localhost User xavier Port 3000 IdentityFile /path/to/node1-id_rsa ProxyJump ubuntu@myEC2And that was it! Thanks @StephaneChazelas
SSH config for connecting to host via reverse SSH tunnel
ssh-add does not honour the configuration file. It just adds the key to the agent. The ssh client would try to use the key ~/.ssh/id_rsa_bull when connecting to either of gg-root or ss-root (due to the IdentityFile configuration). If that key is available in the agent, then it will be used from there, otherwise the key will be used from file (and a password may have to be provided if the key has one associated with it). The keys in the agent would also be used when connecting to any other host not configured with a specific IdentityFile in ~/.ssh/config. This means that the configuration restricts the keys used for authenticating with particular hosts, but the shown configuration does not stop the "bull key" from being used with other hosts.
Background I use a 4096-bit RSA key-pair for authorizing access to my server. By ssh_config files I am referring to ~/.ssh/config and /etc/ssh/ssh_config. Here's what my ~/.ssh/config looks like: Host gg-root HostName 172.47.95.122Host ss-root HostName 172.47.95.123# Common for my servers Host gg-root ss-root User root Port 32001 IdentitiesOnly yes IdentityFile ~/.ssh/id_rsa_bull# Common for all Host * AddKeysToAgent yesNow, I can simply connect to my server via SSH with the following (without any further configuration): ssh gg-root ssh ss-rootThing is, I need to add the private key ~/.ssh/id_rsa_bull to the system's SSH agent to make it easily available to other apps like FileZilla which I use for SFTP. (Esp. because I don't like that FileZilla needs an unencrypted private key as .ppk.) So, I either run this command each time: ssh-add ~/.ssh/id_rsa_pepperOr have this in my ~/.profile: ssh-add ~/.ssh/id_rsa_pepper > /dev/null 2>&1Question When I add the key to the system's SSH agent using ssh-add, does it honor the declarations I've made in ssh_config file(s)? Specifically, does it make sure that ~/.ssh/id_rsa_pepper is only used for 172.47.95.{122,123}? Based on how I interpreted what I read, I believe it should. If I am wrong, please enlighten me as to how I should go about adding a private key to the system's SSH agent where the said private key is only used for stated hosts?EDIT: Based on Answer This is what my ~/.ssh/config looks like now: Host gg-root HostName 172.47.95.122Host ss-root HostName 172.47.95.123# Common for my servers Host gg-root ss-root User root Port 32001 IdentityFile ~/.ssh/id_rsa_bull# Common for all Host * AddKeysToAgent yes IdentitiesOnly yes
Does ssh-add honor the declarations made in ssh_config file(s)?
See these answers: https://unix.stackexchange.com/a/44343 (using ProxyCommand) and https://askubuntu.com/a/1268036 (using Match host ... exec)
i cannot run a command before connect with ssh to remote server using ~/.ssh/config file. I have tried with options "ProxyCommand" and "LocalCommand" but it doesn't work.ProxyCommand: seems it run the command, but after that doesn't ask me the password of ssh connection LocalCommand: run the command only if the connection successful
SSH config file - Run command before connection
Suppose you used a different hostname when you want to use tmux eg for sshfs : ssh user@remotehostbut for tmux ssh user@remotehost_tmuxand then in your ~/.ssh/config have a section specific for the host remotehost_tmux eg. # Global Options #UseRoaming no# Hostname specific options Host <hostname>_tmux RemoteCommand /bin/sh -c 'tmux has-session && exec tmux attach || exec tmux' Hostname <hostname> #
In my ~/.ssh/config file I have the following option: RemoteCommand /bin/sh -c 'tmux has-session && exec tmux attach || exec tmux' This automatically starts tmux and connects to an existing session if possible when connecting via ssh. This causes sshfs to fail to connect with the error read: Connection reset by peer. Is there a way to apply this options selectively only when connecting with ssh and not when attempting to mount a filesystem with sshfs? Note that I still want to load the remainder of the options in that file for sshfs, since they are still relevant. Using sshfs -F /dev/null is not an option. I could of course create two separate configuration files for ssh and sshfs, but that would require a bunch of duplication that seems unecessary.
Is it possible to have conditional options in ~/.ssh/config based on the calling application (ssh or sshfs)?
Regarding /home/user/.ssh/config, that's purely for ssh client itself, used on the machine initiating the ssh connection. So not useful here. Question has been updated saying you've discounted the prospect of adding Match User or Match Group entries into /etc/ssh/sshd_config, because you want a user-specific config. If you want certain users to be chrooted into their home directory, you could leverage group membership instead, such as this, specifically using Match Group and ChrootDirectory %h. Match Group jailed Banner none ChrootDirectory %h PasswordAuthentication no AllowTcpForwarding yes X11Forwarding no AllowAgentForwarding no ForceCommand /bin/false
I'm trying to restrict an SSH-tunnel user. # sudo cat /home/user/.ssh/config Banner none ChrootDirectory /home/%u PasswordAuthentication no AllowTcpForwarding yes X11Forwarding no AllowAgentForwarding no ForceCommand /bin/falseHowever, none of these seem to have any effect. When I prepend /home/user/.ssh/authorized_keys with no-pty,no-agent-forwarding,no-X11-forwarding,command="/bin/false" it works, but I'd like to also include these directives into permanent configuration. Is it possible to restrict a user this way without updating /etc/ssh/sshd_config? UPDATE I know about Match User and Match Group; the point is to have this in a user-specific config.
Put `ForceCommand` in a user-specific configuration file
I can expect the settings in /etc/ssh/ssh_config to be ignored?Yes. ssh reads -F command-line option, which will set the config variable: case 'F': config = optarg; break;and later on calls the process_config_files function, which either:reads config specified on command-line, or reads the other two (/etc/ssh/ssh_config and ~/.ssh/config) files.Additionally specifying none on command-line (-F none) will cause that no configuration file is loaded. See linked function source code for more details how this switch is handled.
If there is no -F switch and there is an /home/me/.ssh/config file that I can expect the settings in /etc/ssh/ssh_config to be ignored or do the settings in my home directory just supplement the global configuration the way they would if I specified them with a -o stanza? For reference, The ssh man page says that the -F switch does the following.Specifies an alternative per-user configuration file. If a configuration file is given on the command line, the system-wide configuration file (/etc/ssh/ssh_config) will be ignored. The default for the per-user configuration file is ~/.ssh/config.
Does the default per user .ssh/config file override all options in system wide ssh_config? [duplicate]
I figured out some working syntax, maybe it could be cleaned up, but it works. Host *.gc User me ProxyCommand gcloud compute --project "myproject" ssh --zone "myzone" me@$(basename %h .gc) --command="nc 0.0.0.0 22"
I would like to use my ssh config to use a google cloud cli (gcloud) to connect to google compute instances. (This is a follow-on to another question I asked, that had a working solution, but didn't address this part of my question) The desired functionality is ssh <instance-name>.gc would connect me to the gcloud instance. To connect to the gcloud instance I can run: /home/me/google-cloud-sdk/bin/gcloud compute --project "myproject" ssh --zone "myzone" me@<instance-name>So I added an entry to my .ssh/config: Host *.gc ProxyCommand /home/me/google-cloud-sdk/bin/gcloud compute --project "myproject" ssh --zone "myzone" me@$(basename %h .gc)I then run ssh <instance-name>.gc and get: # ssh <instance-name>.gc Pseudo-terminal will not be allocated because stdin is not a terminal. -bash: line 1: $'SSH-2.0-OpenSSH_8.0\r': command not foundIt seems to establish a connection, but I don't have a prompt to type at, so I press ctrl-c to kill it. I could make an alias to achieve similar behavior, but I want to be able to use it with other entries in my ssh config, so I can use it as a jumpbox.Debugging It could be that I am misusing ProxyCommand, I get the same behavior if I replace the gcloud command with ssh me@<instace-ip> in the config file. If this is the case, is there an alternative config that help me to achieve my goal? gcloud uses ssh under the hood, you can pass arguments to ssh after adding a --. I have tried adding a -- -t to force pseudo-terminal allocation, without change.
ssh config to start session with google cloud compute instance using gcloud cli command
According to the ssh_config manual page:Since the first obtained value for each parameter is used, more host-specific declarations should be given near the beginning of the file, and general defaults at the end.You should change the order of your configuration values, first set the host-specific ones then the general ones: Host machin Hostname machin User me User root
I would like to connect to each server using the root user and to machin server using me user. I edit .ssh/config User root Host machin Hostname machin User meWhen I type ssh machinI get root@machin's password:What is wrong with my config?
ssh config change user for one host
This was explained in this question: https://superuser.com/questions/22535/what-is-randomart-produced-by-ssh-keygen. It doesn't really have any use for the user generating the key, rather it's for ease of validation. Personally. would you rather look at this: (Please note this is a host key example) 2048 1b:b8:c2:f4:7b:b5:44:be:fa:64:d6:eb:e6:2f:b8:fa 192.168.1.84 (RSA) 2048 16:27:ac:a5:76:28:2d:36:63:1b:56:4d:eb:df:a6:48 gist.github.com,207.97.227.243 (RSA) 2048 a2:95:9a:aa:0a:3e:17:f4:ac:96:5b:13:3b:c8:0a:7c 192.168.2.17 (RSA) 2048 16:27:ac:a5:76:28:2d:36:63:1b:56:4d:eb:df:a6:48 github.com,207.97.227.239 (RSA)Which, being a human, it'd take you a good while longer to verify, or this: 2048 16:27:ac:a5:76:28:2d:36:63:1b:56:4d:eb:df:a6:48 gist.github.com,207.97.227.243 (RSA) +--[ RSA 2048]----+ | . | | + . | | . B . | | o * + | | X * S | | + O o . . | | . E . o | | . . o | | . . | +-----------------+ 2048 16:27:ac:a5:76:28:2d:36:63:1b:56:4d:eb:df:a6:48 github.com,207.97.227.239 (RSA) +--[ RSA 2048]----+ | . | | + . | | . B . | | o * + | | X * S | | + O o . . | | . E . o | | . . o | | . . | +-----------------+Examples pulled from http://sanscourier.com/blog/2011/08/31/what-the-what-are-ssh-fingerprint-randomarts-and-why-should-i-care/ Essentially, the random art generated by the user's keys can also be used in the same sort of way. If the image generated initially is different from the current image of the key, for example if you had moved a key, then the key had likely been tampered with, corrupted, or replaced. This, from the other question is a really good read: http://users.ece.cmu.edu/~adrian/projects/validation/validation.pdf
The ssh-keygen generates the following output: The key fingerprint is: dd:e7:25:b3:e2:5b:d9:f0:25:28:9d:50:a2:c9:44:97 user@machine The key's randomart image is: +--[ RSA 2048]----+ | .o o.. | | o +Eo | | + . | | . + o | | S o = * o| | . o @.| | . = o| | . o | | o. | +-----------------+What is the purpose of this image, does it provide any value for the user? Note this is a client (user) key, not a host key.
What's the purpose of the randomart image for user (not host) SSH keys?
The string is base64 encoded. When decoded, it produces the string \0\0\0\vssh-ed25519\0. This identifies the type of the key. In this case an EdDSA key.
Specifically, why are the first 25 characters of ssh Ed25519 public keys always the same? For example, if I make 5 keys with ssh-keygen -o -a 100 -t ed25519, the first 25 characters are always AAAAC3NzaC1lZDI1NTE5AAAAI. I assume this is a preamble or header of some sort, but I would love to know the actual answer.
Why do portions of SSH public (and private) keys overlap?
This tutorial titled: SSH: Convert OpenSSH to SSH2 and vise versa appears to offer what you're looking for. Convert OpenSSH key to SSH2 key Run the OpenSSH version of ssh-keygen on your OpenSSH public key to convert it into the format needed by SSH2 on the remote machine. This must be done on the system running OpenSSH. $ ssh-keygen -e -f ~/.ssh/id_dsa.pub > ~/.ssh/id_dsa_ssh2.pubConvert SSH2 key to OpenSSH key Run the OpenSSH version of ssh-keygen on your ssh2 public key to convert it into the format needed by OpenSSH. This needs to be done on the system running OpenSSH. $ ssh-keygen -i -f ~/.ssh/id_dsa_1024_a.pub > ~/.ssh/id_dsa_1024_a_openssh.pubThe tutorial goes on to show how to both generate the various types of keys and how to export them to other formats. Use this for private & public keys? According to the man page, the answer would be a yes. Looking at the man page for ssh-keygen it states the following for the -e switch: -e This option will read a private or public OpenSSH key file and print the key in RFC 4716 SSH Public Key File Format to stdout. This option allows exporting keys for use by several commercial SSH implementations.But in practice it would appear that ssh-keygen can't convert private keys, only public ones. For example: # Make a new RSA key-pair $ ssh-keygen -t rsa -f newkey# attempt to extract the private key $ ssh-keygen -e -f newkey > newkey_e# attempt to extract the public key $ ssh-keygen -e -f newkey.pub > newkey.pub_e# Notice the supposed extracted private key (newkey_e) and the corresponding extracted public key (newkey.pub_e) have identical `md5sum`'s. $ for i in *;do md5sum $i;done d1bd1c12c4a2b9fee4b5f8f83150cf1a newkey 8b67a7be646918afc7a041119e863be5 newkey_e 13947789d5dcc5322768bd8a2d3f562a newkey.pub 8b67a7be646918afc7a041119e863be5 newkey.pub_eLooking at the resulting extracted keys confirms this: $ grep BEGIN newkey_e newkey.pub_e newkey_e:---- BEGIN SSH2 PUBLIC KEY ---- newkey.pub_e:---- BEGIN SSH2 PUBLIC KEY ----Googling a bit I came across this blurb from an article titled: How do you convert OpenSSH Private key files to SSH. The site seemed to be up and down but looking in Google's cache for this page I found the following blurb:How do you convert OpenSSH Private key files to SSH.com Private key files? It cannot be done by the ssh-keygen program even though most man pages say it can. They discourage it so that you will use multiple public keys. The only problem is that RCF will not allow you to register more than one public key.The article goes on to cover a method for converting a openssh private key to a ssh.com private key through the use of PuTTY's puttygen tool. NOTE: puttygen can be run from Windows & Linux.Open 'puttygen' and generate a 2048 bit rsa public/private key pair. Make sure you add a password after it is generated. Save the public key as "puttystyle.pub" and save the private key as "puttystyle". The putty program and SSH.com programs share a common public-key format but the putty program and OpenSSH have different public-key formats. We will come back to this, later. You should be able to load both puttystyle keys into the putty program. However, the private key formats for putty and SSH.com are not the same and so you will have to create a converted file. Go to the conversions menu and export an SSH.com key. Save it as "sshstyle". Now go back to the conversions menu and export an openssh key. Save it as "openssh". These names are arbitrary and you can choose your own. You will have to change the names for installation on an OpenSSH machine, later. See below.Given the above I worked out the following using puttygen, using our previously generated private/public openssh key-pair: # generate ssh.com private key from private openssh key $ puttygen newkey -O private-sshcom -o newkey.puttygen-sshcom# generate ssh.com public key from private openssh key $ puttygen newkey -O public -o newkey.pub_puttygen-sshcom# generate openssh public key from private openssh key (for confirmation) $ puttygen newkey -O public-openssh -o newkey.pub_puttygen-opensshThe commenting is different so you can't just compare the resulting files, so if you look at the first few lines of the keys, that's a pretty good indicator that the above commands were successful. Comparison of public ssh.com keys: $ tail -n +3 newkey.pub_e | head -1 | cut -c 1-60 AAAAB3NzaC1yc2EAAAADAQABAAABAQDFkZdpmbze9c6pT883rE1i64TJd4wb$ tail -n +3 newkey.pub_puttygen-sshcom | head -1 | cut -c 1-60 AAAAB3NzaC1yc2EAAAADAQABAAABAQDFkZdpmbze9c6pT883rE1i64TJd4wbComparison of public openssh keys: $ cut -c 1-100 newkey.pub ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDFkZdpmbze9c6pT883rE1i64TJd4wbz9x/w6I2DmSZVI9TJa6M9jgGE952QsOY$ cut -c 1-100 newkey.pub_puttygen-openssh ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDFkZdpmbze9c6pT883rE1i64TJd4wbz9x/w6I2DmSZVI9TJa6M9jgGE952QsOY
Is there a way to convert existing pair of OpenSSH keys to the SSH2 (ssh.com format) pair of keys? UPD: since there are some answers about ssh-keygen suddenly appeared, I'll explain where I came from (also it will be a nice answer on "what have you tried?"). $> diff --report-identical-files <(ssh-keygen -e -f ~/.ssh/id_dsa) <(ssh-keygen -e -f ~/.ssh/id_dsa.pub) Files /tmp/zshAGGWAK and /tmp/zshPZiIr6 are identicalIn other words, ssh-keygen returns same keys for private and public input keys (hashes of original files are obviously different, I've checked them twice to ensure that they are valid private and public keys). It seems to be that ssh-keygen generates only public key for private or public input key. I'm doing it wrong or it is a normal behavior?
Convert OpenSSH private key into SSH2 private key
Lines in the known_hosts file are not encrypted, they are hashed. You can't decrypt them, because they're not encrypted. You can't “unhash” them, because that what a hash is all about — given the hash, it's impossible¹ to discover the original string. The only way to “unhash” is to guess the original string and verify your guess. If you have a list of host names, you can pass them to ssh-keygen -F and replace them by the host name. while read host comment; do found=$(ssh-keygen -F "$host" | grep -v '^#' | sed "s/^[^ ]*/$host/") if [ -n "$found" ]; then ssh-keygen -R "$host" echo "$found" >>~/.ssh/known_hosts fi done <hostnames.txt¹ In a practical sense, i.e. it would take all the computers existing today longer than the present age of the universe to do it.
I try to find a script to decrypt (unhash) the ssh hostnames in the known_hosts file by passing a list of the hostnamses. So, to do exactly the reverse of: ssh-keygen -H -f known_hostsOr also, to do the same as this if the ssh config HashKnownHosts is set to No: ssh-keygen -R know-host.com -f known_hosts ssh-keyscan -H know-host.com >> known_hostsBut without re-downloading the host key (caused by ssh-keyscan). Something like: ssh-keygen --decrypt -f known_hosts --hostnames hostnames.txtWhere hostnames.txt contains a list of hostnames.
How to decrypt hostnames of a crypted .ssh/known_hosts with a list of the hostnames?
ssh # ssh -o "FingerprintHash sha256" testhost The authenticity of host 'testhost (256.257.258.259)' can't be established. ECDSA key fingerprint is SHA256:pYYzsM9jP1Gwn1K9xXjKL2t0HLrasCxBQdvg/mNkuLg.# ssh -o "FingerprintHash md5" testhost The authenticity of host 'testhost (256.257.258.259)' can't be established. ECDSA key fingerprint is MD5:de:31:72:30:d0:e2:72:5b:5a:1c:b8:39:bf:57:d6:4a.ssh-keyscan & ssh-keygen Another approach is to download the public key to a system which supports both MD5 and SHA256 hashes: # ssh-keyscan testhost >testhost.ssh-keyscan# cat testhost.ssh-keyscan testhost ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItb... testhost ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC0U... testhost ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIMKHh...# ssh-keygen -lf testhost.ssh-keyscan -E sha256 256 SHA256:pYYzsM9jP1Gwn1K9xXjKL2t0HLrasCxBQdvg/mNkuLg testhost (ECDSA) 2048 SHA256:bj+7fjKSRldiv1LXOCTudb6piun2G01LYwq/OMToWSs testhost (RSA) 256 SHA256:hZ4KFg6D+99tO3xRyl5HpA8XymkGuEPDVyoszIw3Uko testhost (ED25519)# ssh-keygen -lf testhost.ssh-keyscan -E md5 256 MD5:de:31:72:30:d0:e2:72:5b:5a:1c:b8:39:bf:57:d6:4a testhost (ECDSA) 2048 MD5:d5:6b:eb:71:7b:2e:b8:85:7f:e1:56:f3:be:49:3d:2e testhost (RSA) 256 MD5:e6:16:94:b5:16:19:40:41:26:e9:f8:f5:f7:e7:04:03 testhost (ED25519)
When I log in to an SSH server/host I get asked whether the hash of its public key is correct, like this: # ssh 1.2.3.4 The authenticity of host '[1.2.3.4]:22 ([[1.2.3.4]:22)' can't be established. RSA key fingerprint is SHA256:CxIuAEc3SZThY9XobrjJIHN61OTItAU0Emz0v/+15wY. Are you sure you want to continue connecting (yes/no)? no Host key verification failed.In order to be able to compare, I used this command on the SSH server previously and saved the results to a file on the client: # ssh-keygen -lf /etc/ssh/ssh_host_rsa_key.pub 2048 f6:bf:4d:d4:bd:d6:f3:da:29:a3:c3:42:96:26:4a:41 /etc/ssh/ssh_host_rsa_key.pub (RSA)For some great reason (no doubt) one of these commands uses a different (newer?) way of displaying the hash, thereby helping man-in-the-middle attackers enormously because it requires a non-trivial conversion to compare these. How do I compare these two hashes, or better: force one command to use the other's format? The -E option to ssh-keygen is not available on the server.
How to compare different SSH fingerprint (public key hash) formats?
Is the restart of sshd needed?Not usually. Linux distributions usually ship with a default configuration that allows public key authentication, so you usually don't even have to edit configuration to enable it, and so restarting is unnecessary. Even in the case that you had to do something with sshd_config, you'd only have to restart it only once after editing that file, not for each edit after of the authorized keys file. Note that you don't even have to restart sshd. From man sshd:sshd rereads its configuration file when it receives a hangup signal, SIGHUP, by executing itself with the name and options it was started with, e.g. /usr/sbin/sshd.And the typical systemd service for sshd recognizes this, so you can do systemctl reload sshd instead.If sshd is restarted, is there a service outage at that time?Depends on your definition of service outage. A simple restart of sshd will not kill existing ssh connections, but new connections wouldn't be accepted until sshd finishes restarting.
I am trying to add a public key to a server but I don't want to restart the sshd service for it to take effect. The reason is that restarting the ssh service seems to be disruptive for other users who could use the ssh service at that time. Most documentation suggest to add a public key to $HOME/.ssh/authorized_keys and then to restart the sshd service (systemctl restart sshd). The OS of interest is Linux. My questions are:Is the restart of sshd needed? If sshd is restarted, is there a service outage at that time? Is there a way to set up passwordless auth using ssh without needing to restart the sshd service after adding new public keys to $HOME/.ssh/authorized_keys?
Add key to authorized_users without needing to restart sshd
Generally, you should not include any secrets in Docker images. See this answer for more on this topic. Docker does not support interactive builds for good reasons as explained in this issue. If you really need to do this, you can use docker commit like so: docker build -t thirsty_darwin_base /path/to/Dockerfile docker run -it --name=thirsty_darwin_changes thirsty_darwin_base /bin/bash # do interactive stuff in the shell, then exit docker commit thirsty_darwin_changes thirsty_darwinNow thirsty_darwin has your interactive changes. Update: Docker has released more comprehensive secrets management since this answer was written.
I build container from below Dockerfile: FROM ubuntu:14.04 ... RUN apt-get update && apt-get install -y vim #RUN ssh-keygen -f /root/.ssh/id_rsa -N strongpass123$%^ RUN ssh-keygen -f /root/.ssh/id_rsa ...I do it quite rarely, but there is many command before using of ssh-keygen and after it. I know that I can do it from script through docker exec -it thirsty_darwin sh script.sh and then tag image and then use chaining of containers (images), but it is not as clear solution as I want. Even worst case is with ssh-add ~/.ssh/id_rsa when I have to use expect tool. Expect tool has hardcoded my password. I do not want to do it.
Can I build a Docker container from Dockerfile in an interactive way with allocation of some pseudo TTY?
You can use this format: [hostname]:2121, as it is stored in the known_hosts file (note, you need to use the square brackets!): ssh-keygen -H -F "[hostname]:2121"Proof of concept (transcript of my minimal test case): $ echo "[hostname]:2121 ssh-rsa AAA...==" > known_hosts $ ssh-keygen -Hf known_hosts known_hosts updated. Original contents retained as known_hosts.old WARNING: known_hosts.old contains unhashed entries Delete this file to ensure privacy of hostnames $ ssh-keygen -H -F "[hostname]:2121" -f known_hosts |1|R21497dX9jN052A92GSoVFbuTPM=|lRtIr6O564EaFG0SsIulNAWpcrM= ssh-rsa AAA...==You might need to use IP address instead of hostname, but it should generally work.
I need to add a check if the hostname is already present in the known_hosts file. Normally I would do something like that: ssh-keygen -H -F hostnameHowever, that does not seem to work for me in this particular case. I connect to the host using port 2102, like that: ssh user@myhost -p 2102I was asked to add the hostname to the known_hosts file, I say yes. After that I run ssh-keygen -H -F myhost but receive empty result. To make the matter worse, the known_hosts is hashed. That works perfectly with port 22, so if I login to ssh user@myotherhost, save the known host and run ssh-keygen -H -F myotherhost I receive the exact line from the file. So, how can I adjust the command to work with port 2102?
Check presence of a hostname under custom port in known_hosts
Use ssh together with tee -a file: < /root/.ssh/authorized_keys sshpass -p "$pass" ssh root@"$remote_host" "tee -a ~/.ssh/authorized_keys"or ssh with cat >> file if you prefer: < /root/.ssh/authorized_keys sshpass -p "$pass" ssh root@"$remote_host" "cat >> ~/.ssh/authorized_keys"Both tee and cat will read from stdin, which is sent to ssh with < file. The difference is, that tee, unlike >> will print what it appends. Note: The double quotes are needed, otherwise the >> or ~ will be interpreted by your shell before sending it to ssh command.
I used in my bash script the follwing cli , in order to send the public key to remote machine sshpass -p $pass scp /root/.ssh/authorized_keys root@$remote_host:~/.ssh/authorized_keysbut since we want to append the public keyes from other host then I am searching the approach top append in bash I know that the option is to use ">>" but how to use the append with my approach ? or maybe other solution ?
how to append public keys to remote host instead of copy it
Solution: I used the below command to get it worked $ ssh-keygen-g3 --key-format openssh2 --import-private-key /home/jbadmin/.ssh2/id_rsa_2048_a /home/jbadmin/.ssh2/id_rsa_2048_a_openssh.pem Imported private key in /home/jbadmin/.ssh2/id_rsa_2048_a to /home/jbadmin/.ssh2/id_rsa_2048_a_openssh.pem.
When i try to convert SSH2 RSA format based private key to .pem format, using openssl i am getting the below error. [jbadmin@xxxxxxx .ssh2]$ openssl req -x509 -key /home/jbadmin/.ssh2/id_rsa_2048_a -nodes -days 365 -newkey rsa:2048 -out id_rsa_2048_a.pem unable to load Private Key 139994671441736:error:0906D06C:PEM routines:PEM_read_bio:no start line:pem_lib.c:703:Expecting: ANY PRIVATE KEYMy Private Key: [[emailprotected]]$ cat id_rsa_2048_a ---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ---- Subject: jbadmin Comment: "2048-bit rsa, jbadmin@x01bicallapp1a, Tue Dec 29 2015 11:38:\ ---------------------------- ---------------------------- ---- END SSH2 ENCRYPTED PRIVATE KEY ----Please suggest me if there is any other way of doing it using openssl or ssh-keygen-g3 EDIT1: Tried below option, still same issue [jbadmin@x01bicallapp1a .ssh2]$ openssl rsa -outform PEM -in /home/jbadmin/.ssh2/id_rsa_2048_a -out /home/jbadmin/.ssh2/id_rsa_2048_a.pem unable to load Private Key 140493432293192:error:0906D06C:PEM routines:PEM_read_bio:no start line:pem_lib.c:703:Expecting: ANY PRIVATE KEY
Converting SSH2 RSA Private Key to .pem using openssl
That's how they are written; OpenSSH emits the public key material via a PEM_write_RSAPublicKey(stdout, k->rsa) call in the do_convert_to_pem function of ssh-keygen.c, while OpenSSL operates instead on the given private key. With OpenSSH, I'd imagine that the majority of cases would be to convert the public key into a form usable on some foreign server, with the private key remaining private on the client system, so operating on the public key of the keypair makes sense. With OpenSSL, there is no "get a public key into a form suitable for some other SSH server" concern, so that code operates directly on the private key. Different code, different intentions, different results.
I generated my public/private key pair using ssh-keygen -t rsa -b 2048 -vand then needed a .pem file and followed this https://serverfault.com/questions/706336/how-to-get-a-pem-file-from-ssh-key-pair ssh-keygen -f id_rsa -e -m pem -----BEGIN RSA PUBLIC KEY-----but then i found this https://gist.github.com/mingfang/4aba327add0807fa5e7f openssl rsa -in ~/.ssh/id_rsa -outform pem -----BEGIN RSA PRIVATE KEY-----why is the output different?
pem file difference - ssh-keygen vs openssl
Locate the host key file on the server: me@server:~$ ls /etc/dropbear/ authorized_keys config dropbear_rsa_host_keyUse dropbearkey to get the public key portion and fingerprint of that host key: me@server:~$ sudo dropbearkey -y -f /etc/dropbear/dropbear_rsa_host_key Public key portion is: ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCk/0IEQhlDHfe3jd1MafWLEsTMFADflBWiODik6CnHXmXUrp1XmQ0fo16ffRxupnIuieU44VZkfCP8MX+WIVMRc/+UOJAox7U+v7B3T9H0a4ZeB48NyPdUCZ9MVSbk+kWmHn+UoXtPdMZ/htQ13XHJLHU8h2I+4dTUs1TYWeW4b8LppRexUJPCjdc9YxmkwI+ctHs6I1oguqSy6IP+aAlK0+QkNrG8HeFe1Nmg2iL5SuYfJCIgxJylK+s6KVMpzVPv7VNX3bSt1NJvf2etowR7kzTZs+uCJyzdILO2p5yAo9V80/zzwyqV+exPHUjD/SE9tYjEBkzKKNo215xQvAzV me@server Fingerprint: sha1!! 41:b0:5e:af:8c:4d:2b:ae:fd:75:7d:f1:d5:35:e1:49:14:2e:08:12The hash algorithm will be different, depending on your version. Pipe the public key portion into ssh-keygen to use a specific hash algorithm: me@server:~$ sudo dropbearkey -y -f /etc/dropbear/dropbear_rsa_host_key | ssh-keygen -l -f - -E sha256 2048 SHA256:NycCxoRiiSAGA7Rvlnuf1gU8pazIpXJKZ3ukdivyam8 me@server (RSA) me@server:~$ sudo dropbearkey -y -f /etc/dropbear/dropbear_rsa_host_key | ssh-keygen -l -f - -E sha1 2048 SHA1:QbBer4xNK679dX3x1TahSRMuLBI me@server (RSA) me@server:~$ sudo dropbearkey -y -f /etc/dropbear/dropbear_rsa_host_key | ssh-keygen -l -f - -E md5 2048 MD5:bb:36:37:3e:ae:36:69:d3:6d:63:b8:a3:97:c3:78:60 me@server (RSA)
When I connect to my Dropbear SSH server for the first time, I get the following message: me@laptop:~$ ssh me@server The authenticity of host 'server' can't be established. RSA key fingerprint is SHA256:NycCxoRiiSAGA7Rvlnuf1gU8pazIpXJKZ3ukdivyam8. Are you sure you want to continue connecting (yes/no)? To make sure that this is the correct server, I want to compare the stated fingerprint from that message to the server's real fingerprint. How can I find out the server's RSA host key fingerprint?
How to verify fingerprint of Dropbear RSA host key?
ssh-keygen -r generates a SSHFP record. That's something you put in a DNS entry to say indicate the host key corresponding to a host name. This allows someone who wants to log into your machine to know what host key to expect, assuming that they trust the DNS record (which in practice means that it must be obtained using DNSSEC). So naturally ssh-keygen -r looks for the host key of your machine. It isn't interested in a user key —if you force it to read a user key, it might work, but the result isn't useful. ssh-keygen -r looks at /etc/ssh_host_*_key.pub, or wherever the SSH server has been configured to look for the host's keys. If you don't have an SSH server set up on your machine, you have no use for an SSHFP record, so it isn't a problem that ssh-keygen -r doesn't find a key.
Short Question I'm assuming that ssh-keygen -r hostname uses a default public key. I would have thought that it would default to ~/.ssh/id_rsa.pub, but that does not appear to be the case. So what is it doing? Long Version My experience with the OpenSSH command-line utilities is that they either prompt the user for any missing arguments or fall back to standard default values. But for ssh-keygen -r this does not appear to be the case. When I run the ssh-keygen -r command without specifying a public key (e.g. ssh-keygen -r hostname), I get the following output: no keys found.I would expect it to default to my public key, e.g. ~/.ssh/id_rsa.pub. However, this does not appear to be the case, since when I pass in this public key explicitly (e.g. ssh-keygen -r hostname -f ~/.ssh/id_rsa.pub) I instead get output of the following form: hostname IN SSHFP 1 1 5d6c87ef4e8f4f59974f05723ff3dc0cffc9c4b4 hostname IN SSHFP 1 2 8fa151e7f3ba43fa89c240ab236f0313aea1fe9f9e9f4e5b8f084ca0008399edMoreover, the man page for ssh-keygen shows the following syntax for the ssh-keygen -r command: ssh-keygen -r hostname [-f input_keyfile] [-g]Since the -f input_keyfile flag is denoted as being optional, I would expect ssh-keygen to do something other than just print an error message. So, if ssh-keygen -r hostname does not use ~/.ssh/id_rsa.pub as its default public key, and it doesn't prompt the user to specify a public key, then what is it doing? Is it defaulting to some other path? If so, what path is that? NOTE: I'm running OpenSSH Version 7.6 on macOS High Sierra (Mac OS X Version 10.13.6).
What does `ssh-keygen -r` do if a public key is not specified?
If the new server only supports key authentication, you've jumped the gun as stated by @dr01. Assuming your new server still allows password connections, the only "key exchange" that seems possible is this: 1) generate your key on newmachine 2) log into existing server using your already configured key 3) scp newuser@newmachine:/path/to/generated/pubkey ~/newuser_newmachine_pubkey 4) cat ~/newuser_newmachine_pubkey >> ~/.ssh/authorized_keys This manually does the same thing that ssh-copy-id would have done, except "pulls" the key from the new box, rather than ssh-copy-id "pushing" to a remote server from the new box.
I configured my server to not allow password authentication. Now I have a new machine in a remote location, how is it possible for me to generate an ssh key and do an ssh-copy-id to the server if the server doesn't allow password authentication?
How to copy public key to the server that doesn't allow password?
Things have changed slightly now. As a result GNOME 3.28 now wraps OpenSSH's ssh-agent, which gives it the same level of support as OpenSSH. Reference - Archlinux wiki - GNOME/KeyringKnown issues Cannot handle ECDSA and Ed25519 keys As of January 2018, GNOME Keyring doesn't handle ECDSA nor Ed25519 keys. You can turn to other SSH agents if you need support for those.Note: As of GNOME 3.28, gnome-keyring replaced its SSH agent implementation with a wrapper around the ssh-agent tool that comes with openssh. As a result, any type of key supported by the upstream ssh-agent is now also supported by gnome-keyring, including ECDSA and Ed25519 keys.If you still find that you're behind this particular version this Gist shows how you can use keychain to workaround this issue, titled: SSH with ed25519 (curve25519) + GNOME-KeyRing. Referencesnew openssh key format and bcrypt pbkdf
Does gnome-keyring support SSH private keys that are saved in the newer OpenSSH file format? Will Gnome Keyring automatically import those private keys? In more detail: When generating a SSH private key, ssh-keygen can save the private key in the newer OpenSSH format (rather than the "more compatible PEM format"). With this format, the private key file begins with "-----BEGIN OPENSSH PRIVATE KEY-----". I just generated a new RSA private key for SSH and saved it in the newer format, using ssh-keygen -t rsa -b 3072 -o -a 16. Now Gnome Keyring doesn't seem to be able to load that private key. In contrast, everything seems to work fine when using ssh-agent. When using Gnome Keyring with this new private key, I see the following error messages in /var/log/messages: gnome-keyring-daemon[10904]: invalid or unrecognized private SSH key: [key id] gnome-keyring-daemon[10904]: signing of the data failed: The operation failedand when I try to run ssh, I see the following error message in my terminal: sign_and_send_pubkey: signing failed: agent refused operationIf it's relevant, I'm using Fedora 25 with MATE, with gnome-keyring-3.20.0-1.fc25.x86_64.
Does Gnome Keyring support new-format OpenSSH private keys?
Generally speaking SSH keys identify clients, not servers (well, at least for the keys in ~/.ssh). The recommended approach is to generate one key per client, as you’ve done effectively, and to add all the appropriate public keys to ~/.ssh/authorized_keys on the servers/accounts you need to access. So on your Macbook Pro, you wouldn’t add the new server’s key, you’d add your existing key (stored on the Macbook) to the new server, typically by using ssh-copy-id <username>@<server>If that doesn’t work, cat ~/.ssh/id_rsa.pubon your Macbook and copy/paste that at the end of ~/.ssh/authorized_keys on the server. Each account you need to use on each server will end up with a ~/.ssh/authorized_keys looking something like ssh-rsa AAAAuifi4poojaixahV8thaQu3eQueex0iequ7Eephua4sai8liwiezaic8othisieseepheexaa1zohdouk5ooxas0aoN9ouFa3ejuiK2odahy8Opaen0Niech4Vaegiphagh4EileiHuchoovusu3awahmo4hooShoocoshi3zohw4ieShaivoora7ruuy7igii3UkeeNg5oph6ohN4ciepaifee8ipas9Gei4cee1SohSoo2oCh5ieta5ohQu6eu5PhoomuxoowigaeH2ophau0xo5phoosh3mah7cheD3ioph1FeeZaudiMei4eighish3deixeiceangah5peeT8EeCheipaiLoonaaPhiej0toYe6== user1@host1 ssh-rsa AAAAsaengaitoh4eiteshijee8ohFichah1chaesh4Oeroh2Chae8aich2os1akoh4Waifee5dai3roethah9oojahnietaexo0ia0xiegheixaiwo8aeshui8uZ4chooCohtei8ooMieloo0pahghaeShooth3zae7eigoSe9arei0lohpeij4aeJ3sahfahviaNiejoozeu1zooth8meibooph5IeGuun1lothiur6aleaw8shuof6fah7ooboophoo8nae6aipieshahcae4ShochohZoh4gohX7aes7aes4bo1eiNaeng7Eeghoh6Ge3Maenoh0qui1eiphahWotahGai8ohYohchuubohp3va5dohs== user2@host1 ssh-rsa AAAA3Zohquoh8UavooveiF0aGho8tokaduih4eosai4feiCoophie7ekisuoNii0raizaighahfaik6aibeviojabee1Sheifo8mae0tiecei4Bai8gaiyahvo1eememofiesai0Teyooghah6iovi1zaibie3aePaFeishie0Pheitahka0FaisieVeuceekooSoopoox7Ahhaed2oi6Faeph1airaizee7Aeg8Aiya2oongaC9ing6iGheeg8chei1ogheighieghie1Apode3shibai5eit8oa5shahDaic0shishie0ies7Aijee5ohk1aetha1Quieyafu2oa0Ahwee3mu9tae4AebeiveeFiewohj== user1@host2The lines will wrap in most editors, so it won’t look quite like the above when viewed; but there is only one line per key. Each line takes the form [options] key-type public-key commentThe important part in this is the middle section which is the base64-encoded public key. Any user with a matching private key will be allowed on the server. The key-type is usually ssh-rsa nowadays, but you can expect to see other types become more popular in the future (such as ssh-ed255519). This depends on the options given when the key was generated. The comment is only there to help people identify the keys, so that once in a while someone can go through the list of authorized keys and make sensible decisions about whether to keep a key or not (disabling a key is as easy as commenting the line out with a # at the start of the file). Typically the comment is the username and hostname corresponding to the generated key (/i.e./ your username when you ran ssh-keygen and the hostname of the client computer). The optional options (there aren’t any in the example above) allow you to control what the users are allowed to do on the server, and/or to constrain the keys (requiring them to be signed by a specific certificate authority for example). For details, see the sshd manpage (search for “AUTHORIZED_KEYS FILE FORMAT”).
I created a key for logging into a server (using ssh-keygen) with the name id_rsa, and so in my .ssh directory there is id_rsa.pub and id_rsa. The reason I used this name, is because when I tried other names, they didn't work with my server (I couldn't log in for some reason). I setup a new server today (and generated the key on a different computer). But the key names is also id_rsa. So how do I use the same key on my macbook pro (OSX), which already has a key named id_rsa, which is still in use (I can't get rid of it, as I need to use it to log into some other servers) ?
How to merge keys, or handle keys with the same file name?
The key is randomly generated. There's nothing more special to its origin than that. Meaning that as long as only you hold the private key, there is no need to replace it. In SSH, a user key is generally used to identify a combination of user & origin system. Meaning the key is not shared among users on the same system, or the same user on multiple systems. Though this is not a technical limitation, as you can break either of these rules without issue. It's just good security practice. In a public key (id_rsa.pub), the last field is a comment. The ssh-keygen command typically puts your username & hostname as the last field. This serves no purpose other than as a comment to identify the key. As for why it puts username & hostname, see the previous paragraph. To directly answer your question, "When should I regenerate the key pairs?": You should regenerate the key when the key has been compromised, and has potentially been obtained by someone else. At this time you should also revoke the previous public key from all remote systems which trust it (the authorized_keys file). That is literally the only reason. If you reinstall the OS, change hostname, etc, you do not need to recreate the key. Though you can if you'd like.
I use the ssh-keygen -t rsa to generate the RSA key pairs. I see that in the id_rsa.pub file, I see the username and the hostname. But I want to know that what elements will affects the key pairs. For example, if I change the host ip, need I regenerate the key pairs? And the hostname? or even I reinstall the operating system? When should I regenerate the key pairs?
What elements affects the key pairs generated by ssh-keygen?
If you want to change the hostname for an existing hashed host, edit your known_hosts file, replacing the hashed hostname with the plaintext hostname you wish associated with that key, and rehash the file: ssh-keygen -HIf you want to generate hashes for a list of hostnames without disturbing your known_hosts, create a file combining the hostnames you wish to hash with a valid key copied out of an existing known_hosts : sample.bar.com ecdsa-sha2-nistp256 AAAAE2... other.bar.com ecdsa-sha2-nistp256 AAAAE2... diff.domain.org ecdsa-sha2-nistp256 AAAAE2...Then hash this file using ssh-keygen : ssh-keygen -f mytestfile -H
Is there an easy way to generate hashed hostnames to be added to the ~/.ssh/known_hosts file? I'd like to add a @cert-authority line to the ~/.ssh/known_hosts file. Obviously the ssh-keygen command would not get the CA cert. Ithink it also needs a connection to the server, and I'mnot sure Ican get it to hash a wildcard. So, how would I hash "*.bar.com", for example, so that it can be used in the ~/.ssh/known_hosts file? Edit: Having thought about it, hashed wildcards probably can't work, as it would be too difficult for the client to match a wildcard after it has been hashed. But, if I can still get a method to hash a domain without requiring a connection to the server (as ssh-keygen does), that would be great.
Generate hashed name for SSH known_hosts
You are conflating two different technologies, openssh and openssl. It appears you need only the former. As you have already created an ssh key pair, you just need to copy the public key to the server you intend to ssh to. The correct way to do this is: $ ssh-copy-id username@<server-ip>Replace username and <server-ip> with the user and IP address of your server.
I have generated the keys in Ubuntu 14.04 system using the following commands to use with ssh. ssh-keygen -t rsa -b 2048 openssl rsa -in id_rsa -outform pem > pk_rsa.pem openssl rsa -in pk_rsa.pem -pubout -out my_key.pemI have copied the my_key.pem to my local which is OSX. Trying to ssh into the Ubuntu using the below command ssh -v -i ./my_key.pem [emailprotected] OpenSSH_7.4p1, LibreSSL 2.5.0 debug1: Reading configuration data /etc/ssh/ssh_config debug1: Connecting to 192.168.113.137 [192.168.113.137] port 22. debug1: Connection established. debug1: key_load_public: No such file or directory debug1: identity file ./ubu14.pem type -1 debug1: key_load_public: No such file or directory debug1: identity file ./ubu14.pem-cert type -1 debug1: Enabling compatibility mode for protocol 2.0 debug1: Local version string SSH-2.0-OpenSSH_7.4 debug1: Remote protocol version 2.0, remote software version OpenSSH_6.6.1p1 Ubuntu-2ubuntu2.8 debug1: match: OpenSSH_6.6.1p1 Ubuntu-2ubuntu2.8 pat OpenSSH_6.6.1* compat 0x04000000 debug1: Authenticating to 192.168.113.137:22 as 'ubuntu' debug1: SSH2_MSG_KEXINIT sent debug1: SSH2_MSG_KEXINIT received debug1: kex: algorithm: [emailprotected] debug1: kex: host key algorithm: ecdsa-sha2-nistp256 debug1: kex: server->client cipher: [emailprotected] MAC: <implicit> compression: none debug1: kex: client->server cipher: [emailprotected] MAC: <implicit> compression: none debug1: expecting SSH2_MSG_KEX_ECDH_REPLY debug1: Server host key: ecdsa-sha2-nistp256 SHA256:KDokJiZiQ9ZflT5Jm5B8krQ8XgsEEgUjQjg+h6C4Gqo debug1: Host '192.168.113.137' is known and matches the ECDSA host key. debug1: Found key in /Users/macdev/.ssh/known_hosts:11 debug1: rekey after 134217728 blocks debug1: SSH2_MSG_NEWKEYS sent debug1: expecting SSH2_MSG_NEWKEYS debug1: SSH2_MSG_NEWKEYS received debug1: rekey after 134217728 blocks debug1: SSH2_MSG_SERVICE_ACCEPT received debug1: Authentications that can continue: publickey,password debug1: Next authentication method: publickey debug1: Trying private key: ./my_key.pem Enter passphrase for key './my_key.pem': debug1: Next authentication method: password [emailprotected]'s password: Is there way to fix this issue.
SSH asking me for passphrase which doesn't have any passphrase
Thank you @xhienne (comment link) for your suggestion. Adding the following to ssh_config appears to have solved the problem: Match User testuser IdentityFile ~/.ssh/id_rsa-testThis block should be placed above Host * to send id_rsa-test ahead of id_rsa for testuser.
I'm looking for a way to set a specific SSH key while logging to a remote host with a particular username. Is this possible within the SSH config file? For example: Use key "id_rsa-test" for username "testuser": ssh testuser@host1 ssh testuser@host2 ssh testuser@host3Use key "id_rsa" for all other users. ssh root@host1 ssh admin@host2 ssh [emailprotected]Is there a way to configure this?
Use X SSH key when logging in to Y remote user?
Config settings for the SSH server are often in /etc/ssh/sshd_config but the first thing I would check is the location and the permissions of the public key and its parent directory that you copied to the server. Noting that correct permissions of authorized_keys on the remote are critical for ssh to work - and hence why we use ssh-copy-id and not simply copying the public key to the remote. To understand this it may be useful to breakdown what the ssh-copy-id does. First thing it does is secure copy id_rsa.pub over to the target server i.e. scp -P port $HOME/.ssh/id_rsa.pub username@ipaddress:destination_pathand place in ~/.ssh/ of the remote machine. it will also rename id_rsa.pub to authorized_keys so you end up with $ ~/.ssh/authorized_keyson remote machine. It also sets the permissions which is critical i.e. authorized_keys file must be no less secure than -rw------- 1 wbarlow wbarlow 802 Nov 25 13:54 authorized_keysand .ssh directory cannot be less secure than 755 e.g. drwx------ 2 wbarlow wbarlow 4096 Jul 29 00:30 .sshI tend to use the command ssh-copy-id -i ~/.ssh/id_rsa.pub remote_user@remoteIPthat way the specific key I want gets onto the remote, but I don't think that would be your problem,as I suspect ssh will check all available private keys on your local machine when trying to establish a connection. Also, as always, make sure to check the basic permissions of the containing folders ($HOME) so that other users/programs have appropriate file privileges .
After running successfully, my build script attempts to copy the final binary onto my FTP server using the scp command. Since the build takes a while, I don't want to be prompted for my password every time, so I tried to set up an SSH-keypair. [wbarlow@build-machine]$ ssh-keygen Generating public/private rsa key pair. Enter file in which to save the key (/home/wbarlow/.ssh/id_rsa): Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /home/wbarlow/.ssh/id_rsa. Your public key has been saved in /home/wbarlow/.ssh/id_rsa.pub. The key fingerprint is: 7f:b9:c7:a8:1b:77:ce:f8:b6:2a:e3:da:30:68:72:b7 wbarlow@build-machine[wbarlow@build-machine]$ ssh-copy-id wbarlow@ftp-server wbarlow@ftp-server's password: Now try logging into the machine, with "ssh 'wbarlow@ftp-server'", and check in: ~/.ssh/authorized_keysto make sure we haven't added extra keys that you weren't expecting.Then I tried to sign into my ftp-server, but I was still prompted for a password. I confirmed that the freshly created key was present. [wbarlow@build-machine]$ ssh wbarlow@ftp-server wbarlow@ftp-server's password: [wbarlow@ftp-server]$ cat ~/.ssh/authorized_keys ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDGUbr4vUeiY7D6sSrsHm469QAqCClchL 7h/HZ7TAc+1F2KsTTF078OSINqzz8NpKJqhlEusLn644PzYn9LmGTIc7IsMG9s+B2n4bZX 9Ypb0VqLSqTgfE2I0j84+SfAQ6MvGJQ0NupIXxXbaMLDlNq1cetnR8NeN+9JeBq4sI8p/a ijFVARQ7/XSKwQQN30Nl6flTEM1CTDECJs5YsPOu3P54mF6PG2mBdFra6+VQfAZ6fboq9O d24VNHLYVtUdK5RpWgx8agUalov0xq/3m2VeC5arrYpCVH1rGx6EMxoQS25kk7t9mzBUCj ulXGWQX2DPR/Em0OIfvVfe/l4xtFfH wbarlow@build-machineI am able to use the public key to authenticate with other machines (namely, my Git repository host), so I don't think that the problem is on the client-side. So -- how can I check that the FTP server is configured to accept authorized keys, and what sort of keys is it configured to accept? How can I check that the keys are being stored in the expected place (my home directory on ftp-server is /var/ftp/wbarlow/, but I've also tried copying the .ssh folder from there to /home/wbarlow/.)?My .ssh directory is mode 700, and my authorized_keys file is mode 600. I've also tried using 755 for the .ssh directory.I found my /etc/ssh/sshd_config file on the ftp-server. I won't post the whole thing, but it does have the following lines: RSAAuthentication yes PubkeyAuthentication yes AuthorizedKeysFile .ssh/authorized_keys# To disable tunneled clear text passwords, change to no here! #PasswordAuthentication yes #PermitEmptyPasswords no PasswordAuthentication yes# Change to no to disable s/key passwords #ChallengeResponseAuthentication yes ChallengeResponseAuthentication noAs far as I can tell from the documentation, I think these lines are set correctly for what I want to do (s/key is something unrelated to ssh keypairs, right?).Below is the verbose output while connecting. [wbarlow@build-machine]:~$ ssh -v wbarlow@ftp-server OpenSSH_6.1p1 Debian-4, OpenSSL 1.0.1c 10 May 2012 debug1: Reading configuration data /etc/ssh/ssh_config debug1: /etc/ssh/ssh_config line 19: Applying options for * debug1: Connecting to ftp-server [(ip hidden)] port 22. debug1: Connection established. debug1: identity file /home/wbarlow/.ssh/id_rsa type 1 debug1: Checking blacklist file /usr/share/ssh/blacklist.RSA-2048 debug1: Checking blacklist file /etc/ssh/blacklist.RSA-2048 debug1: identity file /home/wbarlow/.ssh/id_rsa-cert type -1 debug1: identity file /home/wbarlow/.ssh/id_dsa type -1 debug1: identity file /home/wbarlow/.ssh/id_dsa-cert type -1 debug1: identity file /home/wbarlow/.ssh/id_ecdsa type -1 debug1: identity file /home/wbarlow/.ssh/id_ecdsa-cert type -1 debug1: Remote protocol version 2.0, remote software version OpenSSH_5.1 debug1: match: OpenSSH_5.1 pat OpenSSH_5* debug1: Enabling compatibility mode for protocol 2.0 debug1: Local version string SSH-2.0-OpenSSH_6.1p1 Debian-4 debug1: SSH2_MSG_KEXINIT sent debug1: SSH2_MSG_KEXINIT received debug1: kex: server->client aes128-ctr hmac-md5 none debug1: kex: client->server aes128-ctr hmac-md5 none debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP debug1: SSH2_MSG_KEX_DH_GEX_INIT sent debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY debug1: Server host key: RSA [SNIP] debug1: Host 'ftp-server' is known and matches the RSA host key. debug1: Found key in /home/wbarlow/.ssh/known_hosts:1 debug1: ssh_rsa_verify: signature correct debug1: SSH2_MSG_NEWKEYS sent debug1: expecting SSH2_MSG_NEWKEYS debug1: SSH2_MSG_NEWKEYS received debug1: Roaming not allowed by server debug1: SSH2_MSG_SERVICE_REQUEST sent debug1: SSH2_MSG_SERVICE_ACCEPT received debug1: Authentications that can continue: publickey,gssapi-with-mic,password debug1: Next authentication method: gssapi-with-mic debug1: Unspecified GSS failure. Minor code may provide more information Cannot determine realm for numeric host addressdebug1: Unspecified GSS failure. Minor code may provide more information Cannot determine realm for numeric host addressdebug1: Unspecified GSS failure. Minor code may provide more informationdebug1: Unspecified GSS failure. Minor code may provide more information Cannot determine realm for numeric host addressdebug1: Next authentication method: publickey debug1: Offering RSA public key: /home/wbarlow/.ssh/id_rsa debug1: Authentications that can continue: publickey,gssapi-with-mic,password debug1: Trying private key: /home/wbarlow/.ssh/id_dsa debug1: Trying private key: /home/wbarlow/.ssh/id_ecdsa debug1: Next authentication method: password wbarlow@ftp-server's password:
How to know if I can use ssh keypairs?
You can use the option -i to specify to ssh which identity file it should use. Also have you checked with ssh - v what really happen? I mean the keys are really not used or are they used but doesn't match?
I just recently started a VPS using Fedora. Upon creation of the VPS I was asked if I wanted to use SSH keys (which I did). Now, to connect as root to the VPS, I do not need to enter a password. Now I want to create a pair (or just reuse the same key) for user1 for use while using ssh. First I tried to paste the id_rsa.pub folder while logged in as user1 in the ~/.ssh/ folder. Still asks for password upon sshThen I added a authorized_keys file that was identical to the id_rsa.pub file. Still asks for password upon sshThen I chmod the permissions to the .ssh folder to 644 however, when I try to ssh login as user1.Still asks for password upon sshHow can I use the same public ssh key on a user account that I have for the root account. Where to I put these files, and what is the difference between having a id_rsa.pub file and an authorized_keys file?
Fedora, where to put my ssh keys to login? [duplicate]
Make sure your key is added to /home/normaluser/.ssh/authorized_keys Authorized keys are per user, meaning that just because a key can be used to log into another user doesn't mean you can use it to log in as any user.
On a remote server I want to create a normal user and ONLY allow access via a key but I do NOT want to create the account with a password first and then disable password access later. In my admin account on the remote server I have done the following: sudo adduser --disabled-password normaluserTrying to connect as 'normaluser' is rejected, as desired with:normaluser@server: Permission denied (publickey)According to adduser man page:The --disabled-password option will not set a password, but login is still possible (for example with SSH RSA keys).Not being sure how ssh keys should be generated in this instance, I sudo su to the normaluser account and generated keys using ssh-keygen. I've then tried to use the public and the private key file (copied to my local machine) to then ssh into the remote machine as normaluser, specifying the appropriate key file with ssh -i but I am still getting access denied (publickey)
How to generate keys after creating user with adduser --disabled-password
Your .ssh directory can't be world accessible: chmod 700 ~/.sshshould fix it
I created a public/private key pair using the ssh-keygen -t rsa in my ~/.ssh folder. I then copied the key over using the ssh-copy-id [emailprotected] command and received this notification. Number of key(s) added: 2I tried logging in but was still prompted for a password. I ran a find / -name id_rsa.pub command and searched my remote server's .ssh folder but couldn't find the master key anywhere. I tried chmod with both go-rwx and 777 permissions on the pub key but to no avail. Why is the file not getting copied, yet I receive no error messages? EDIT: I added the -v tag to the ssh command and got this output OpenSSH_6.2p2, OSSLShim 0.9.8r 8 Dec 2011 debug1: Reading configuration data /etc/ssh_config debug1: /etc/ssh_config line 20: Applying options for * debug1: Connecting to [servername] [ipaddress] port 22. debug1: Connection established. debug1: identity file /Users/william.roberts/.ssh/id_rsa type 1 debug1: identity file /Users/william.roberts/.ssh/id_rsa-cert type -1 debug1: identity file /Users/william.roberts/.ssh/id_dsa type -1 debug1: identity file /Users/william.roberts/.ssh/id_dsa-cert type -1 debug1: Enabling compatibility mode for protocol 2.0 debug1: Local version string SSH-2.0-OpenSSH_6.2 debug1: Remote protocol version 2.0, remote software version OpenSSH_5.3 debug1: match: OpenSSH_5.3 pat OpenSSH_5* debug1: SSH2_MSG_KEXINIT sent debug1: SSH2_MSG_KEXINIT received debug1: kex: server->client aes128-ctr hmac-md5 none debug1: kex: client->server aes128-ctr hmac-md5 none debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP debug1: SSH2_MSG_KEX_DH_GEX_INIT sent debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY debug1: Server host key: RSA 7c:3a:61:86:ec:53:40:c3:b0:5e:c2:9f:f4:bf:35:64 debug1: Host '[servername]' is known and matches the RSA host key. debug1: Found key in /Users/william.roberts/.ssh/known_hosts:7 debug1: ssh_rsa_verify: signature correct debug1: SSH2_MSG_NEWKEYS sent debug1: expecting SSH2_MSG_NEWKEYS debug1: SSH2_MSG_NEWKEYS received debug1: Roaming not allowed by server debug1: SSH2_MSG_SERVICE_REQUEST sent debug1: SSH2_MSG_SERVICE_ACCEPT received debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic,password debug1: Next authentication method: publickey debug1: Offering RSA public key: /Users/william.roberts/.ssh/id_rsa debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic,password debug1: Offering RSA public key: /Users/william.roberts/.ssh/other_rsa debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic,password debug1: Offering RSA public key: /Users/william.roberts/.ssh/id_rsa debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic,password debug1: Trying private key: /Users/william.roberts/.ssh/id_dsa debug1: Next authentication method: passwordEdit 2: output of ls -la .ssh drwxrwxrwx 2 root root 4096 Dec 10 19:15 . dr-xr-x---. 5 root root 4096 Nov 19 22:44 .. -rw------- 1 root root 3019 Dec 10 19:51 authorized_keys -rw-r--r-- 1 root root 427 Nov 24 19:40 known_hosts
ssh public key not getting copied over
In ssh speak, that's a comment, not a name. But I find "name" more fitting, as that's exactly what it's used for... so.you can just change the name, arbitrarily, using ssh-keygen -c. Not part of the key itself. you can specify the "name" with the -C command line option to ssh-keygen.For future readers / reference: Had you known to look for "comment", you'd have found this info in man ssh-keygen.
I would like to generate an ssh key pair for a service account on one machine to access another machine via ssh. When I generate the key with my user, my username is embedded in the public key. E.g. This has [emailprotected] in the public key ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDHt9bVJZZ78NE8xYXDfPyXE4+1ajONSRzBAW7WCRPWj4oc2X7dm1usZQIq9kca0b8IaFXtiMdUoCtkqGQz9Jd8/7zHkM5Fo+SR1NvsK8TNPlHkHQzlLxvn9OAjfKfDwjUCc7OskVxYwDpsWK6s0E0cRGJhI4Ccaws5EV6sgveuPJ1Bi/lmnz1CUKgsxlqHza0EH4eiCx5fb+k1lF71+o7urKiG2TUmCOEocwmjJ6WieDE+MrNSmPtOUD8Oo01QF9/PttdE3VsUATYgB/GhWmENH/o7hdyckq6fnUmpAaomOPeiCbw5pOHiadhDwiGH7gU/GfAugmFrrfv6sb1hkM980ufB7uvShpaMYa4eLiaAN+TIvmvpodkDeS5NMLPzcRN+cnAsflZa8pb2VeXmVWTIc2buYoWzI7Mc1iuQbnQwJh8WbjruDvgUCHNaR+GBDpOh17Qq/AR1ew+J8wo3a6foyxFHWji9gj4dlSuaZfyTfBdiBo6Xux0iyQrzDL9QTTc= [emailprotected]NOTE: You cannot log on as the service account to generate the key - hence I need to generate it from my login. Is there a way to generate the key from my login, but the generated key have the service account name.
how to create an ssh key-pair for a service account
$ cat /tmp/test -----BEGIN OPENSSH PRIVATE KEY----- b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABlwAAAAdzc2gtcn NhAAAAAwEAAQAAAYEArKk9jKvP/kwZq5GAog449OK5LzjppL5DbQhlJcqntzqu88+6WDHr lQM0IKyHgEkRDim8MrmisK2eIJrmj99STJEBPu7jgJ0q2ASToSeFiU8FB+yrV9ZmelwJ7f 1rD5vp3TlROAc08pIKb2YVHE4KfLzAncGXVETldTuGDAHgXQWIlhZDBGbkt8pwM/Kt10j4 t7snCGKNWm8c9K943Tv3J+okI+vdv3V5a2dfoCW+9cnNE57jotE/LTli5CwuxFcX5zc1ON i/l0opxWAfhi4sCZBiaMnMfSX9kvYNl0cnaIRvzB3/CoSkxq9OJicQ2dDtXVu1LUvUrtHl abfthPq2UttHzwZWEVxR5ZYfW3v7hXgc5MrOMabffAu9ALs7eDv+3gnVNbp1Qv5Jl9L+R9 VXO7OVxmWhPGrLlVZJr078rNfZBLt4UEkiM9kswF0w+IVdUYm/VBJBSgfqCSo1xXxy9u8z zywqTn6/MW0zInF5nxcfBb8zomZUEmJeoZnWlGN9AAAFgDrUKVw61ClcAAAAB3NzaC1yc2 EAAAGBAKypPYyrz/5MGauRgKIOOPTiuS846aS+Q20IZSXKp7c6rvPPulgx65UDNCCsh4BJ EQ4pvDK5orCtniCa5o/fUkyRAT7u44CdKtgEk6EnhYlPBQfsq1fWZnpcCe39aw+b6d05UT gHNPKSCm9mFRxOCny8wJ3Bl1RE5XU7hgwB4F0FiJYWQwRm5LfKcDPyrddI+Le7JwhijVpv HPSveN079yfqJCPr3b91eWtnX6AlvvXJzROe46LRPy05YuQsLsRXF+c3NTjYv5dKKcVgH4 YuLAmQYmjJzH0l/ZL2DZdHJ2iEb8wd/wqEpMavTiYnENnQ7V1btS1L1K7R5Wm37YT6tlLb R88GVhFcUeWWH1t7+4V4HOTKzjGm33wLvQC7O3g7/t4J1TW6dUL+SZfS/kfVVzuzlcZloT xqy5VWSa9O/KzX2QS7eFBJIjPZLMBdMPiFXVGJv1QSQUoH6gkqNcV8cvbvM88sKk5+vzFt MyJxeZ8XHwW/M6JmVBJiXqGZ1pRjfQAAAAMBAAEAAAGBAKRYr3JvtBo8+444gDVAzmwiRt yxEowyYmGtRQH05TFeVVtTle8PDUuYcgzLzGqKogZWKYIq+rWrfMFSUDYP/vlMaOAraTdp 4ncd3BvgT5ZENei2GN4SARdk9jqnJjoEUVW2kh1/lqFx6ybgByYbDpZu3/UJaW7X6YVuNA jH3HUOqFUcOYw+GGTs92IrE9fA6KWSKfQsQpoa+3fYcnY69uXyU5Yxk7ADNKDME9SPOTYh cOfFLK40+Cqm3f+MIrPWpSRO0Dcselcq/YpxdjmcaXVnVj/XqTGQwCn8akCtgjarcaOkw5 zO/UN1aphzCgojhH0HzV67ufG2alO1BYz5Hd1dyPX8itdDOUcT6x1FRoiFkmvkbTVXl3FM JynzmPzuHRnmHrolhNy8ZeaE63I27TDDausddWQ7Pn03LFazwJKYvCoxWBlT+8bMmiY2AC C5iNiMgxqudh90CLoyPg3eyIJ8La2l/I+CcZuQsFG4dx9QaFQxJUQCLtW0CNWATflRzQAA AMAV8M+lLQUOBGs0S4bVnqTvRmERY81YRyhB+sOYGMdY/6jW+BvFqDCP/y1wTmPgFA/tUI oAvc2LkX47lEHsV/pJa7Dk0FK6rNRL3puu2M+bWFcHAIxizHNzTcYPlTz89d9TVg1TvvmR r5DCNAvGAD+b1947YqNH+Dt3yw5XzYu3EacU4lyeYpaAoeB1P3+eJv5Y06isQO7r1S9DWI wr24nyKxE1Ur1kh+lbSm7+cJgf4s8sJi/d5PB4dagjGfa/dOgAAADBANxHZ+NQnsyAEqBX gGC/5VCDbvzFBZWvYGkRn3TJkIDIZvN142MYDkbG5JDxm7k/JJ0Cbqx1GY5S4BZ1ogju/g u8qIz/lMIwpmLAd09n14xVXOVLKnN9GpQ0505+CDaNIK2ANcMqB4auovJcVNTkIVrxVjs4 vEEyVjI5ze+jBNqJstEuk6IaSEzcMckXSdMDcfnPh7b2QanL6KkCUhxaK1ftG/K+4znEtx pHYbDy7uEwx4whDhyZn0EAQZ+NZ8leHwAAAMEAyKkKv2treH+WPO0S+d7KTNJRJv4tiiOE VBTL+evXzVxXLwQDCoQ4sV0+Ye7j9D75kGDIoxnkJZiCab8WMDeFP78awDVYru7My739K/ v2LwS0yeMSDNitvoDN+wu5kn2oskMoZRDTG2EHKxreMdu6vHEPRsmx6zmx53ogRFsa+jnV DHrfSx7nQL28lrWvcDkQ6apvdjLj8i/ZYP9KC9f2VfYpqgI/1ONDG3ndXgn8cFkLdSnF2Y 1yWVGKN2wVIFLjAAAACWppcmlAdDUwMAE= -----END OPENSSH PRIVATE KEY-----$ ssh-keygen -p -f /tmp/test -m PEM Key has comment 'jiri@t500' Enter new passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved with the new passphrase.$ cat /tmp/test -----BEGIN RSA PRIVATE KEY----- MIIG5QIBAAKCAYEArKk9jKvP/kwZq5GAog449OK5LzjppL5DbQhlJcqntzqu88+6 WDHrlQM0IKyHgEkRDim8MrmisK2eIJrmj99STJEBPu7jgJ0q2ASToSeFiU8FB+yr V9ZmelwJ7f1rD5vp3TlROAc08pIKb2YVHE4KfLzAncGXVETldTuGDAHgXQWIlhZD BGbkt8pwM/Kt10j4t7snCGKNWm8c9K943Tv3J+okI+vdv3V5a2dfoCW+9cnNE57j otE/LTli5CwuxFcX5zc1ONi/l0opxWAfhi4sCZBiaMnMfSX9kvYNl0cnaIRvzB3/ CoSkxq9OJicQ2dDtXVu1LUvUrtHlabfthPq2UttHzwZWEVxR5ZYfW3v7hXgc5MrO MabffAu9ALs7eDv+3gnVNbp1Qv5Jl9L+R9VXO7OVxmWhPGrLlVZJr078rNfZBLt4 UEkiM9kswF0w+IVdUYm/VBJBSgfqCSo1xXxy9u8zzywqTn6/MW0zInF5nxcfBb8z omZUEmJeoZnWlGN9AgMBAAECggGBAKRYr3JvtBo8+444gDVAzmwiRtyxEowyYmGt RQH05TFeVVtTle8PDUuYcgzLzGqKogZWKYIq+rWrfMFSUDYP/vlMaOAraTdp4ncd 3BvgT5ZENei2GN4SARdk9jqnJjoEUVW2kh1/lqFx6ybgByYbDpZu3/UJaW7X6YVu NAjH3HUOqFUcOYw+GGTs92IrE9fA6KWSKfQsQpoa+3fYcnY69uXyU5Yxk7ADNKDM E9SPOTYhcOfFLK40+Cqm3f+MIrPWpSRO0Dcselcq/YpxdjmcaXVnVj/XqTGQwCn8 akCtgjarcaOkw5zO/UN1aphzCgojhH0HzV67ufG2alO1BYz5Hd1dyPX8itdDOUcT 6x1FRoiFkmvkbTVXl3FMJynzmPzuHRnmHrolhNy8ZeaE63I27TDDausddWQ7Pn03 LFazwJKYvCoxWBlT+8bMmiY2ACC5iNiMgxqudh90CLoyPg3eyIJ8La2l/I+CcZuQ sFG4dx9QaFQxJUQCLtW0CNWATflRzQKBwQDcR2fjUJ7MgBKgV4Bgv+VQg278xQWV r2BpEZ90yZCAyGbzdeNjGA5GxuSQ8Zu5PySdAm6sdRmOUuAWdaII7v4LvKiM/5TC MKZiwHdPZ9eMVVzlSypzfRqUNOdOfgg2jSCtgDXDKgeGrqLyXFTU5CFa8VY7OLxB MlYyOc3vowTaibLRLpOiGkhM3DHJF0nTA3H5z4e29kGpy+ipAlIcWitX7RvyvuM5 xLcaR2Gw8u7hMMeMIQ4cmZ9BAEGfjWfJXh8CgcEAyKkKv2treH+WPO0S+d7KTNJR Jv4tiiOEVBTL+evXzVxXLwQDCoQ4sV0+Ye7j9D75kGDIoxnkJZiCab8WMDeFP78a wDVYru7My739K/v2LwS0yeMSDNitvoDN+wu5kn2oskMoZRDTG2EHKxreMdu6vHEP Rsmx6zmx53ogRFsa+jnVDHrfSx7nQL28lrWvcDkQ6apvdjLj8i/ZYP9KC9f2VfYp qgI/1ONDG3ndXgn8cFkLdSnF2Y1yWVGKN2wVIFLjAoHBAKz7/l+Kzkn2QapdTNmt mN2TebNS3cHgyat5RWmnaK1Zs095wqntGDkItDIHKq1dItmSMWuJQhp8hrHcivTN CgAZlZu0khO1tNRUJN3cxG7WEm+Wia3MDvVYXlVLsBN23LSjvJSZCvP/bMM7MvtE c9VBNOCo+12PtBUZQ9nugT9FZ4HSO+nPDfwd55LtkPH/AKCXExLhbEt1cC5ZPjY5 sVQJRitpMHQLQWeHqvYUsPdzISGwS662DVQ0aVRs7ZY7LQKBwQCOrRuWRgQRlu61 fYB7qL1BaF4JkrvAuEZUHsF2gApe2+Sl6n1bEe7ZtkowClONjOWYkii3SCaf0NQR 6qwVNrUJQZH8zzGymNuHlxyYFLzUa808q7de6QaJKT7M3WZi0fSMZBIp4o+orRIS xTTuUKVzbhSFqc5XShvEUmL1F66T82EYUZnJ6TxXHVIl+yO2cO0kqGo+qirIPtub C4qT50ghkTnIx3apobpKpBkRz5nuLHJoKX6jlN6UwdS8WZ6f8C8CgcAV8M+lLQUO BGs0S4bVnqTvRmERY81YRyhB+sOYGMdY/6jW+BvFqDCP/y1wTmPgFA/tUIoAvc2L kX47lEHsV/pJa7Dk0FK6rNRL3puu2M+bWFcHAIxizHNzTcYPlTz89d9TVg1TvvmR r5DCNAvGAD+b1947YqNH+Dt3yw5XzYu3EacU4lyeYpaAoeB1P3+eJv5Y06isQO7r 1S9DWIwr24nyKxE1Ur1kh+lbSm7+cJgf4s8sJi/d5PB4dagjGfa/dOg= -----END RSA PRIVATE KEY-----
How to convert RFC4716 private keys to PEM private keys in ubuntu 20.04?For our project we generated ssh keys on a device running the latest openssh software. JSch complained about authentication: Exception com.jcraft.jsch.JSchException: Auth fail After a lot of research, including building a minimal git client we discovered a small change to our other key files. The header didn’t start with ​—–BEGIN RSA PRIVATE KEY—– but it started with —–BEGIN OPENSSH PRIVATE KEY—– showing, that this key is formatted in the new default RFC4716 format.I have same question here, but I want to use my original key instead of regenerate one. And I don't want to use GUI applications like PuTTY. I want convert it in scripts. I tried several attempts, non of these works: ssh-keygen -f id_rsa -m 'PEM' -e ssh-keygen -f id_rsa -e -m pem # I got PUBLIC KEY instead of private keyopenssl rsa -in ~/.ssh/id_rsa -outform pem openssl rsa -in id_rsa -pubout -out id_rsa.pub.pem openssl rsa -in ~/.ssh/id_rsaunable to load Private Key # unable to load Private Key # 139920849113728:error:0909006C:PEM routines:get_name:no start line:../crypto/pem/pem_lib.c:745:Expecting: ANY PRIVATE KEYHow do I convert it?
How to convert RFC4716 private keys to PEM private keys?
Firstly, the easiest way to copy SSH keys is by using ssh-copy-id command. Do this for both users. Secondly, to create a reverse tunnel, use the following command (executed on laptop): ssh -fnN -R 3322:localhost:22 serveruser@system-serverThen lastly, connect to the tunneled service. No password will be asked if ssh-copy-id was completed earlier. Execute the following command on your system-server, to start a new SSH session from remote linux server to laptop. ssh -p 3322 laptopuser@localhost
I have two systemsPersonal MacOS Laptop to be referred as system-Laptop having user laptopuser. It does not have "NAT"Server Linux to be referred as system-Server having user serveruser having static IP anyone can connect to.system-Server needs to send ssh commands to system-Laptop using a reverse SSH tunnel as the system-Laptop get dynamic IP and does not have "NAT" Below is how I setup ssh-keys and reverse SSH Step 1: Generated key pair for laptopuser on system-Laptop and copied the public key id_rsa.pub to self ~/.ssh/authorized_keys as well as on system-Server at <serveruserhomedir>/.ssh/authorized_keys Step 2: Generated key pair for serveruser on system-Server and copied the public key id_rsa.pub to self ~/.ssh/authorized_keys as well as on system-Laptop at <laptopuserhomedir>/.ssh/authorized_keys Note: Was able to successfully test this command on system-Laptop -> ssh serveruser@system-Server Step 3: Ran the below command on system-Laptop for reserve ssh tunnelling: ssh -N -R 3322:localhost:22 serveruser@system-Server Step 4: Ran the below command to connect to my Laptop from Linux server: ssh -p 3322 laptopuser@localhost The issue is the above command prompts for the password and once I provide laptopuser password it works. How can I get the above to work passwordless using ssh keys? Did I miss something? Doing this[reverse-ssh] for the very first time so unaware. Below is the debug output of step 4 ssh command: ssh -p 3322 laptopuser@localhost ....... ....... debug1: SSH2_MSG_NEWKEYS sent debug1: expecting SSH2_MSG_NEWKEYS debug3: receive packet: type 21 debug1: SSH2_MSG_NEWKEYS received debug2: set_newkeys: mode 0 debug1: rekey after 134217728 blocks debug2: key: /home/serveruser/.ssh/id_rsa (0x56539b783370) debug2: key: /home/serveruser/.ssh/id_dsa ((nil)) debug2: key: /home/serveruser/.ssh/id_ecdsa ((nil)) debug2: key: /home/serveruser/.ssh/id_ed25519 ((nil)) debug3: send packet: type 5 debug3: receive packet: type 7 debug1: SSH2_MSG_EXT_INFO received debug1: kex_input_ext_info: server-sig-algs=<ssh-ed25519,ssh-rsa,rsa-sha2-256,rsa-sha2-512,ssh-dss,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521> debug3: receive packet: type 6 debug2: service_accept: ssh-userauth debug1: SSH2_MSG_SERVICE_ACCEPT received debug3: send packet: type 50 debug3: receive packet: type 51 debug1: Authentications that can continue: publickey,password,keyboard-interactive debug3: start over, passed a different list publickey,password,keyboard-interactive debug3: preferred gssapi-keyex,gssapi-with-mic,publickey,keyboard-interactive,password debug3: authmethod_lookup publickey debug3: remaining preferred: keyboard-interactive,password debug3: authmethod_is_enabled publickey debug1: Next authentication method: publickey debug1: Offering RSA public key: /home/serveruser/.ssh/id_rsa debug3: send_pubkey_test debug3: send packet: type 50 debug2: we sent a publickey packet, wait for reply debug3: receive packet: type 51 debug1: Authentications that can continue: publickey,password,keyboard-interactive debug1: Trying private key: /home/serveruser/.ssh/id_dsa debug3: no such identity: /home/serveruser/.ssh/id_dsa: No such file or directory debug1: Trying private key: /home/serveruser/.ssh/id_ecdsa debug3: no such identity: /home/serveruser/.ssh/id_ecdsa: No such file or directory debug1: Trying private key: /home/serveruser/.ssh/id_ed25519 debug3: no such identity: /home/serveruser/.ssh/id_ed25519: No such file or directory debug2: we did not send a packet, disable method debug3: authmethod_lookup keyboard-interactive debug3: remaining preferred: password debug3: authmethod_is_enabled keyboard-interactive debug1: Next authentication method: keyboard-interactive debug2: userauth_kbdint debug3: send packet: type 50 debug2: we sent a keyboard-interactive packet, wait for reply debug3: receive packet: type 60 debug2: input_userauth_info_req debug2: input_userauth_info_req: num_prompts 1 Password:[serveruser@system-Server ~]$ ls -ltr /home/serveruser/.ssh/id_rsa -rw------- 1 serveruser serveruser 3243 Jan 15 21:01 /home/serveruser/.ssh/id_rsa
Reverse SSH works but not passwordless. Getting password prompt
First of all you can use -vvv option to get debugging info from ssh. ssh -vvv user@hostSecondly most system will accept only few (about 6) tries, so if you have more ssh keys then you should point specific, because wrong keys might used available challenges from ssh server. (It's configurable by MaxAuthTries parameter in /etc/ssh/sshd_config). To point specific key use -i option ssh -i ~/.ssh/my_key user@hostIf you are sure that problem is on server, you should check at least following:Check ~/.ssh/authorized_keys and ~/.ssh permissions. If you are using SELinux restorecon on /home and check auditlog with sealert If it's still not working check sshd logs.
I'm trying to get two server to connect via ssh keys. These two servers had working ssh key authentication before, but one of them failed and was restored from a backup. Since then, the key does not seem to be working. I've tried the following:Making sure permissions are set correctly Removing all remote entries of the host and starting over Generating a new keyWhen I set this up the first time around, I generated a key with ssh-keygen, and copied it over with ssh-copy-id, and things worked smoothly. Now, even starting over from scratch, that isn't the case. This is a small, isolated environment, so there was nothing complicated going on - I wasn't using ssh-agent, or a passphrase for the key. Reading the remote server's log, I can see the key was accepted, yet it still prompts for password. I'm not really sure what has gone wrong and would be grateful for some direction. Thanks!
SSH key accepted but remote host asks for password
There is a difference between an encrypted key (which is password protected) and a non-encrypted key. All keys are still plaintext files. Below I have generated a key, with no password, and then secured it by adding a password, and you can see how the contents of the file on disk is different: $ ssh-keygen -f ./id_example Generating public/private rsa key pair. Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in ./id_example. Your public key has been saved in ./id_example.pub. The key fingerprint is: SHA256:q1soNjAdOS7sEu/268wb/F0ULMB7a2tmr/n+089Ksu0 user@host The key's randomart image is: +---[RSA 2048]----+ | .. | | ... . | | + .. o | | . o o. .. . | |. = o .S.. | | + = .oo | |. o * ..o.. ... | | o.+ = +=o .=.. | | ..oBo+=+=+.ooEoo| +----[SHA256]-----+ $ cat id_example -----BEGIN RSA PRIVATE KEY----- MIIEogIBAAKCAQEArxyeUk2lJ+pkW2bHXJNFUfWz1z3glvOsHSUxUQjx8leKIKRu [hash truncated fro brevity] hGWfADUrb5nV5Do/mcjBHQDCjrfCpzPHkNrTaZLs4JDxdhX4G0s= -----END RSA PRIVATE KEY----- $ ssh-keygen -p -f ./id_example Enter new passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved with the new passphrase. $ cat id_example -----BEGIN RSA PRIVATE KEY----- Proc-Type: 4,ENCRYPTED DEK-Info: AES-128-CBC,764EDE56E9A89905CD447F1DEF5ED1ABuVjfs7qu4a7RMvycvpvtJA0UUG5UtkZ+eY6ppmxL7oA/54qM/7S5bvgOT1hM0wL+ [hash truncated for brevity] FHCAmqC29+FPHxqG19tII7ndYYU6YDpCQHjUN0TaAI7ikwSmjTiNBfXEZodaHblr -----END RSA PRIVATE KEY-----The actual key is the same, but a key agent will not be able to use the latter key until I unlock it with my passphrase. Either way, I own the file, and it has to exist on disk which means it can be displayed (e. g. with cat). You can also see when I display the revised key that it explicitly shows that it is encrypted.
I thought it was not be possible to view the content of a password-protected private key file without actually inputing a password. Very surprisingly though, I can still see the content of my private key file even though it's well password-protected. Steps: $ ssh-keygen -t ed25519 -o -a 100I then input my password. I wait a bit. Process is finished, then I do a cat as follows: $ cat id_ed25519To my big surprise, I can clearly see my private key. I wanted to know if it was well password-protected. So, I did the following: $ ssh-keygen -p -f ./id_ed25519Indeed, I have to input my “old” password. Otherwise, it does not recognise it! Am I missing something? If my understanding is correct, if my private key file is encrypted, I shouldn't see its content in a text editor, right? I'm completely baffled. System: MacOS Le Capitan, Homebrew
SSH Password-protected Private Key Still Visible
Without knowing the version of OpenSSH you're running, or the distro, it's difficult to answer. However, there are many ways to achieve this. One such way, if you're running a recent version of OpenSSH, is to use the AuthenticationMethods directive in you /etc/ssh/sshd_config file. Example: AuthenticationMethods publickey,keyboard-interactive
I know this is a bit weird. I generated ssh keys on my server, but I still want to force clients to enter a passphrase to be able to SSH to the server,even if they have the key. Is that even possible? Can I set a password on top of the key, and force clients to use both to SSH?
Force ssh to ask for password and public key
Dropbear uses its own format for key storage and public keys are not on file. The dropbearkey binary can be used to generate keys and convert between formats. dropbearkey -y -f /etc/dropbear/dropbear_rsa_host_key > /tmp/ssh_host_rsa_key.pub ssh-keygen -r host.example.net -f /tmp/ssh_host_rsa_key.pubSee https://github.com/mkj/dropbear/blob/master/README for the full story ;)
How to generate SSHFP records for a Dropbear instance at OpenWrt? I have dropbearconvert and openssh-keygen installed, but nothing works. Always invalid format or similar errors. There are two host key files available: /etc/dropbear/dropbear_dss_host_key /etc/dropbear/dropbear_rsa_host_keyAny ideas how to get a SSHFP record?
How to generate SSHFP records with OpenWrt/Dropbear?
POSIX first was a standard in 1988 long before the Single UNIX Specification. It was one of the attempts at unifying all the various UNIX forks and UNIX-like systems. POSIX is an IEEE Standard, but as the IEEE does not own the UNIX® trademark, the standard is not UNIX® though it is based on the existing UNIX API at that time. The first standard POSIX.1 is formally known as IEEE std 1003.1-1988.[1] IEEE charged a substantial fee to obtain a copy of the standard. The Open Group released the Single UNIX Specification (SUSv2) in 1997 based on IEEE's work of the POSIX standard. SUSv3 was released in 2001 from a joint working group between IEEE and The Open Group known as the Austin Group. SUSv3 is also known as POSIX:2001[2]. There is now also POSIX:2004 and POSIX:2008 which is the core of SUSv4. As for what UNIX® is, UNIX® is whatever the current registered trademark holder says it is. Since 1994, that is The Open Group. Novell acquired the UNIX® systems business from AT&T/USL which is where UNIX® was born. In 1994, they sold the right to the UNIX® trademark to X/Open[3] now know as The Open Group. They then sold the UNIX® source code to SCO as UNIXWARE®.[3] UNIX® itself has forked many times[4][5] partly due to AT&T's licensing model. Purchasing UNIX® gave you the complete source of the operating system and the full tool-chain to build it. Modifications to the source can be distributed and used by anyone who owned a license to UNIX® from AT&T. The license fee was in the thousands. BSD was a project at Berkeley which added a number of enhancements to the UNIX® operating system. BSD code was released under a much more liberal license than AT&T's source and did not require a license fee or even a requirement to be distributed with source, unlike the GPL that the GNU Project and Linux use. This has caused a good part of the BSD code to be included with various commercial UNIX forks. By around 4.3BSD, they had nearly replaced any need for the original AT&T UNIX® source code. FreeBSD/NetBSD/OpenBSD are all forks of 4.3BSD that are a complete operating system and have none of the original AT&T source code. Nor do they have right to the UNIX® trademark, but much of their code is used by commercial UNIX operating systems. The Socket API used on UNIX was developed on BSD and the Unix Fast Filesystem code was borrowed and used on various UNIX Operating Systems like Solaris with their own enhancements. Linux was developed in 1991, but was developed from scratch unlike BSD and uses the existing GNU Project which is a clean-room implementation of much of the UNIX user-space. It implements much of POSIX for compatibility and is UNIX-like in design, but it does not have the close connection to AT&T or UNIX® that the BSDs have.
I see POSIX mentioned often and everywhere, and I had assumed it to be the baseline UNIX standard.. until I noticed the following excerpt on a Wikipedia page: The Open Group The Open Group is most famous as the certifying body for the UNIX trademark, and its publication of the Single UNIX Specification technical standard, which extends the POSIX standards and is the official definition of a UNIX system. If the official definition of a UNIX system is an extension of POSIX, then what exactly is POSIX? ,,, It surely seems to be a touchstone of the UNIX world, but I don't know how it fits into the overall picture.
What exactly is POSIX?
Posix defines the standard streams thus:At program start-up, three streams shall be predefined and need not be opened explicitly: standard input (for reading conventional input), standard output (for writing conventional output), and standard error (for writing diagnostic output). When opened, the standard error stream is not fully buffered; the standard input and standard output streams are fully buffered if and only if the stream can be determined not to refer to an interactive device.The GNU C Library describes the standard streams similarly:Variable: FILE * stdout The standard output stream, which is used for normal output from the program. Variable: FILE * stderr The standard error stream, which is used for error messages and diagnostics issued by the program.Thus, standard definitions have little guidance for stream usage beyond “conventional/normal output” and “diagnostic/error output.” In practice, it’s common to redirect either or both of these streams to files and pipelines, where progress indicators will be a problem. Some systems even monitor stderr for output and consider it a sign of problems. Purely auxiliary progress information is therefore problematic on either stream. Instead of sending progress indicators unconditionally to either standard stream, it’s important to recognize that progress output is only appropriate for interactive streams. With that in mind, I recommend writing progress counters only after checking whether the stream is interactive (e.g., with isatty()) or when explicitly enabled by a command-line option. That’s especially important for progress meters that rely on terminal update behavior to make sense, like %-complete bars. For certain very simple progress messages (“Starting X” ... “Done with X”) it’s more reasonable to include the output even for non-interactive streams. In that case, consider how users might interact with the streams, like searching with grep or paging with less or monitoring with tail -f. If it makes sense to see the progress messages in those contexts, they will be much easier to consume from stdout.
Is there an official POSIX, GNU, or other guideline on where progress reports and logging information (things like "Doing foo; foo done") should be printed? Personally, I tend to write them to stderr so I can redirect stdout and get only the program's actual output. I was recently told that this is not good practice since progress reports aren't actually errors and only error messages should be printed to stderr. Both positions make sense, and of course you can choose one or the other depending on the details of what you are doing, but I would like to know if there's a commonly accepted standard for this. I haven't been able to find any specific rules in POSIX, the GNU coding standards, or any other such widely accepted lists of best practices. We have a few similar questions, but they don't address this exact issue:When to use redirection to stderr in shell scripts: The accepted answer suggests what I tend to do, keep the program's final output on stdout and anything else to stderr. However, this is just presented as a user's opinion, albeit supported by arguments. Should the usage message go to stderr or stdout?: This is specific to help messages but cites the GNU coding standard. This is the sort of thing I'm looking for, just not restricted to help messages only.So, are there any official rules on where progress reports and other informative messages (which aren't part of the program's actual output) should be printed?
Do progress reports/logging information belong on stderr or stdout?
The behavior of shell utilities does differ in minor ways between unix variants. There are many unix variants, with a complex history. There are standardisation efforts such as the POSIX standard and its superset the Single UNIX specification. Most systems nowadays implement POSIX:2001, also known as the Single UNIX Specification version 3, with minor deviations and many extensions. The Single Unix specification is not a tutorial, but version 3 is readable if you already have an idea of what a command is doing. You can consult it to know if some feature is standard or an extension of a particular system. A majority of unix users use Linux and haven't used any other variant. Linux comes with GNU utilities, which often have many extensions to the standard. So you'll find quite a lot of code out there that works on Linux but not on other unices, because it relies on those extensions. Regarding sed, consult the sed Single Unix specification for the minimum that every system is supposed to support, the man page on your system for what your implementation supports, and the GNU sed manual for what most people out there use. One of the nonstandard extensions in GNU sed is supporting multiple commands run together. For example, this GNU sed program prints all lines containing an a, but changes b into c first: sed -ne '/a/ {s/b/c/g; p}'{ and } are actually separate commands, so for full portability, you need to specify them either on separate lines (in a file) or in separate -e arguments (on the command line). The lack of a command separator after { and the use of ; as a command separator are common extensions. The lack of a command separator before } is a less common extension. This is standard-compliant: sed -n -e '/a/ {' -e 's/b/c/g' -e p -e '}'This is nonstandard but commonly accepted: sed -ne '/a/ { s/b/c/g; p; }'Another nonstandard but common extension is the use of \n to mean a newline in a s replacement text (the use in a regexp is standard). The portable method is to include backslash-newline in the sed script. Another common extension is \+, \? and \| in regexps to mean one or more, at most one and alternation; portable basic regular expressions have none of these. For example, the first command is a non-portable way of replacing contiguous sequences of whitespace by a newline; the second command is a standards-compliant equivalent. sed -e 's/ \+/\n/' sed -e 's/ */\ /'
I am having some issues in using an answer provided on this site for this question about a sed command to replace a blank line with two other lines of content, and it was brought up if the sed command on Mac OS (10.6.7 for me) is different. I don't think that it is, but was wondering if others on this site thought differently.
Differences between sed on Mac OSX and other "standard" sed?
There is no standard indentation in shell scripts that matters. Slightly less flippant answer:Pick a standard in your team that you can all work to, to simplify things. Use something your editor makes easy so you don't have to fight to stick to the standard.
Java community use 4 spaces as the unit of indentation. 1 Ruby community use 2 spaces that is generally agreed-upon. 2 What's the standard for indentation in shell scripts? 2 or 4 spaces or 1 tab?
What's the standard for indentation in shell scripts? [closed]
The autoconf manual has a section on portable shell programming. Although that's not specifically targeting POSIX, it's probably the most complete collection of what to do and not to do when attempting to write portable shell code.
What resources exist for portable shell programming? The ultimate answer is to test on all targeted platforms, but that's rarely practical. The POSIX / Single UNIX specification is a start, but it tells neither you what the level of support of each implementation is, nor what common extensions exist. You can read the documentation of each implementation, but that's very time consuming and not completely accurate. I seems to me that an ideal format would be some kind of community-annotated version of the POSIX spec, where each feature is annotated by its support level amongst the different implementations. Is there such a thing? Or are there other useful resources?For example, there is Sven Mascheck's shell portability pages, but it's only about syntactic elements and a few built-ins, and only covers old shells. I'm looking for a more comprehensive resource.
Resources for portable shell programming
Unfortunately there is no guarantee of anything being available. However, most systems will have GNU coreutils. That alone provides about 105 commands. You can probably rely on those unless it's an embedded system, which might use BusyBox instead. You can probably also rely on bash, cron, GNU findutils, GNU grep, gzip, iproute2, iputils, man-db, module-init-tools, net-tools, passwd (passwd or shadow), procps, tar, and util-linux. Note that some programs might have some differences between distributions. For example /usr/bin/awk might be gawk or mawk. /bin/sh might be dash or bash in POSIX mode. On some older systems, /usr/bin/host does not have the same syntax as the BIND version, so it might be better to use dig. If you're looking for some standards, the Linux Standard Base defines some commonly found programs, but not all distributions claim to conform to the standard, and some only do so if you install an optional LSB compatibility package. As an example of this, some systems I've seen don't come with lsb_release in a default install. As well as this, the list of commands standardized by POSIX could be helpful. Another approach to your problem is to package your script using each distribution's packaging tools (e.g. RPM for Red Hat, DEB for Debian, etc.) and declare a dependency on any other programs or packages you need. It's a bit of work, but it means users will see a friendlier error message, telling them not just what's missing, but what packages they need to install. More info:RPM - Adding Dependency Information to a Package (historical) RPM - Dependencies Debian - Declaring Relationships Between Packages PKGBUILD - Dependencies
I would like to know which are the standard commands available in every Linux system. For example if you get a debian/ubuntu/redhat/suse/arch/slackware etc, you will always find there commands like: cd, mkdir, ls, echo, grep, sed, awk, ping etc. I know that some of the mentioned commands are shell-builtin but others are not but they are still always there (based on my knowledge and experience so far). On the other hand commands like gawk, parted, traceroute and other quite famous commands are not installed by default in different Linux distributions. I made different web searches but I haven't found a straight forward answer to this. The purpose is that I would like to create a shell script and it should make some sanity checks if the commands used in the script are available in the system. If not, it should prompt the user to install the needed binaries.
Which are the standard commands available in every Linux based distribution?
Console programs typically use curses or one of its successors¹ to build the sorts of text user interfaces you're talking about. These libraries use one of two databases, called termcap and terminfo.² These databases contain maps that tell the library what codes to send to get desired actions with a large number of diverse terminal types. The vast majority of the terminal types you'll find defined in these databases didn't survive the days of real terminals, and so are now only of historical interest. ANSI Terminals Modern Unix terminal emulators³ use the ANSI X3.64 protocol or one of its later variants:ANSI X3.64: A standard for controlling "glass terminals" — as opposed to teletypes — it is based on special sequences of characters which the remote terminal interprets. For instance, if the Unix box wants to tell an ANSI X3.64 compatible terminal to move its cursor to the upper left corner of the screen, it sends the characters ESC [ 1 ; 1 H. The first two characters tell the terminal to expect a control sequence, the 1s are the row and column, and H is the command meaning "move cursor".⁴ Trivia: many PC BBSes used ANSI codes, too. (Still do, actually.) DEC VT100: The first really popular ANSI-compatible glass terminal was Digital Equipment Corporation's VT100. By proving ANSI's de jure standard out in the marketplace, it established a de facto standard that is still important today. Sometimes you see this called the VT102 protocol, that being a later cost-reduced — and therefore more popular — version of the VT100 plus all available expansion options built-in. The DEC terminal protocols are a backwards-compatible series, extending from the first ANSI-compatible model introduced in 1978 (the VT100) up through the VT500 series models produced by Boundless Technologies after they bought the terminal business from DEC in 1995. (Boundless is now out of business, but their terminals still pop up on the used market from time to time.) xterm: A kind of amalgam of ANSI and the VT-whatever standards. Whenever you're using a GUI terminal emulator like xterm or one of its derivatives, you're usually also using the xterm terminal protocol, typically the more modern xterm-color or xterm-color256 variants. Linux: The Linux console also uses an extended variant of the ANSI terminal protocol, in the same spirit as the xterm protocols. Most of its extensions have to do with the differences between a PC and a glass terminal. For example, the IBM keyboard has some keys not on a DEC VT-whatever. (And vice versa.) Some Unix systems have their own console terminal protocol, too. There's the scoansi ANSI X3.64 variant for SCO Unixes, for example.A typical terminal emulator program is something of a mongrel, and doesn't emulate any single terminal model exactly. It might support 96% of all DEC VT escape sequences up through the VT320, yet also support extensions like ANSI color (a VT525 feature) and an arbitrary number of rows and columns. The 4% of codes it doesn't understand may not be missed if your programs don't need those features, even though you've told curses (or whatever) that you want programs using it to use the VT320 protocol. Such a program might advertise itself as VT320 compatible, then, even though, strictly speaking, it is not.⁵ Non-ANSI Terminals There are a few other notable standards that you still sometimes come across:Wyse: One of the earliest independent producers of glass terminals, Wyse started making terminals in the early 1980s before workstation computing began displacing minicomputers. Although Wyse terminals were able to emulate the VT100 and other popular terminal protocols, they also had their own native codes. IBM 3270: Although this is not strictly a "Unix" terminal type, the need to connect Unix systems to IBM mainframes led to the creation of IBM 3270 series terminal emulator programs, which you can still find in use. Emulators for the later IBM 5250 series terminals are also fairly common, most often used these days for connecting to AS/400 and Systemi minicomputers. Tektronix 4014: Before PCs and workstations largely displaced glass terminals and thus made bitmapped graphics a standard feature, there were expensive graphics terminals which drew graphics on the screen in response to text commands similar to the escape sequences described above. Probably the most popular of these was the Tektronix 4010 series. They were quite fun to use. You could write a program that drew a graphic, but then instead of simply running it to draw on your local terminal, you could redirect its output to a file: $ ./my4014program > my-neat-graphicYou could then send that file to someone else, and they could cat it on their Tek terminal to see the graphic without having your program. Part of the charm was how slow these terminals were in drawing, so you could watch the graphic build up over several seconds.Working With Unix Terminal Emulation Today You can find out which terminal standard you're asking libraries like curses to use by looking at the TERM environment variable: $ echo $TERM xterm-colorWhen you ssh to another system, the TERM variable is carried along so the remote Unix box knows how to communicate with your local terminal. Because so many of these protocols are ANSI X3.64 variants, and because the ubiquitous ASCII and UTF-8 character coding standards take care of so much else, an incorrect TERM variable isn't typically catastrophic. Things that tend to break are extended keys like Home and Page Up, Alt-whatever key combinations, and typographical display features like color, boldface, etc.Footnotes:Most commonly, ncurses. There are also outright competitors to the curses API, such as S-Lang. AT&T promulgated terminfo as a replacement for BSD's termcap database, and it was largely successful in replacing it, but there are still programs out there that still use the old termcap database. It is one of the many BSD vs. AT&T differences you can still find on modern systems. My macOS box doesn't have /etc/termcap, but it does have /usr/share/terminfo, whereas a standard installation of FreeBSD is the opposite way around, even though these two OSes are often quite similar at the command line level. minicom, xterm, mintty, GNOME Terminal, Terminal.app, etc. Properly-written Unix programs don't emit these escape sequences directly. Instead, they use one of the libraries mentioned above, telling it to "move the cursor to position (1,1)" or whatever, and the library emits the necessary terminal control codes based on your TERM environment variable setting. This allows the program to work properly no matter what terminal type you run it on. Old text terminals had a lot of strange features that didn't get a lot of use by programs, so many popular terminal emulator programs simply don't implement these features. Common omissions are support for sixel graphics and double-width/double-height text modes. The maintainer of xterm wrote a program called vttest for testing VT terminal emulators such as xterm. You can run it against other terminal emulators to find out which features they do not support.
I was wondering how the "GUI" of a command line application is communicated over a network. Most of the time, it's quite simple (plain text / input) but sometimes it's more complex (aptitude). Is it defined by some sort of standard so that anyone can write their own terminal and that all terminal implementations behave in the same way (colors, positioning, etc.)?
What protocol/standard is used by terminals?
No, that would be a bad idea. cat hugeregularfile.txt > /dev/null and touch -a hugeregularfile.txt are not the same. cat will read the whole file, even if you redirect the output to /dev/null. And reading the whole file might be exactly what you want. For example in order to cache it so that later reads will be significantly faster. The shell can't know your intention. Similarly, a C compiler will never optimize out reading a file, even if you don't look at the stuff you read.
If a shell is asked to perform a probably useless (or partially useless) command known to terminate, such as cat hugeregularfile.txt > /dev/null, can it skip that command's execution (or execute a cheaper equivalent, say, touch -a hugeregularfile.txt)? More generally, is the shell similar to C compilers in that it may perform any transformation on the source code, so long as the externally observable behaviour is as-if the abstract machine evaluated it? EDIT Nota Bene: My question as originally posed had a title that asked whether the shell is permitted to do these optimizations, not whether it should or even whether implementations that can do them exist. I'm interested in the theory more than the practice, although both are welcome.
Is the shell permitted to optimize out useless terminating commands?
Debian Live Standard is Debian without the Graphical User Interface. Debian Live Gnome is Debian Standard with Gnome.
I was wondering, is there any differences between Debian Standard and GNOME versions? Isn't Debian under GNOME by default?
What's the difference between Debian Standard and Gnome?
As written in the manual page, the /etc/networks file is to describe symbolic names for networks. With network, it is meant the network address with tailing .0 at the end. Only simple Class A, B or C networks are supported. In your example the google-dns entry is wrong. It's not a A,B or C network. It's an ip-address-hostname-relationship therefore it belongs to /etc/hosts. Actually the default entry is also not conformant. Lets imagine you have an ip address 192.168.1.5 from your corporate network. An entry in /etc/network could then be: corpname 192.168.1.0When using utilities like route or netstat, those networks are translated (if you don't suppress resolution with the -n flag). A routing table could then look like: Kernel IP routing table Destination Gateway Genmask Flags Metric Ref Use Iface default 192.168.1.1 0.0.0.0 UG 0 0 0 eth0 corpname * 255.255.255.0 U 0 0 0 eth0
What is the practical usage of /etc/networks file? As I understand, one can give names to networks in this file. For example: root@fw-test:~# cat /etc/networks default 0.0.0.0 loopback 127.0.0.0 link-local 169.254.0.0 google-dns 8.8.4.4 root@fw-test:~# However, if I try to use this network name for example in ip utility, it does not work: root@fw-test:~# ip route add google-dns via 104.236.63.1 dev eth0 Error: an inet prefix is expected rather than "google-dns". root@fw-test:~# ip route add 8.8.4.4 via 104.236.64.1 dev eth0 root@fw-test:~#What is the practical usage of /etc/networks file?
practical usage of /etc/networks file
To get a certification you need to pay, and it's actually really expensive. That's why BSD-like and GNU/Linux OS vendors don't apply for it. So there isn't even a reason to check whether GNU/Linux is compliant or not. http://en.wikipedia.org/wiki/Single_UNIX_Specification#Non-registered_Unix-like_systems Most of all, the GNU/Linux distribution follows the Linux Standard Base, which is free of charge, and recognized by almost all Linux vendors. http://en.wikipedia.org/wiki/Linux_Standard_BaseEdit: As my answer is not completely correct, I'll add the @vonbrand comments:Linus (and people involved in the development of other parts of Linux distributions) follow the pragmatic guideline to make it as close to POSIX as is worthwhile. There are parts of POSIX (like the (in)famous STREAMS) that are ill-conceived, impossible to implement efficiently, or just codification of historic relics that should be replaced by something better.... therefore, does it make it harder to obtain a certification?Sure. POSIX mandates some interface, which Linux just won't ever have. Case closed.
I am looking for specific details as to why isn't GNU/Linux currently SUS (Single UNIX Specification) v3 or even better SUS v4 compliant? What application APIs and user utilities does it miss or implement in a non-SUS compliant way?
Why isn't GNU/Linux SUS v3+ compliant?
I'd use .sh (for files in the POSIX sh language, .bash for non-sh-compatible bash files, that is the extension identifies the language the script is written in) for files intended to be sourced (or more generally not intended to be executed), and no extension for files that are meant to be executed. You can also add a: #! /bin/echo Please-sourceshe-bang, so that when executed by mistake (though I'd expect those files should not be given execution permissions, which would already prevent execution), you get a notice that it should be sourced instead.
I was wondering if there is a convention for file type extensions for shell scripts you want to source instead of run. For example:If I want to run this script in a subshell. ./script.sh If I want to remember to run this script from the current shell. . script.source Is there a convention (like POSIX for example) for a filetype in the second example? Something like .source or .sourceme?Update This question does not ask about any opinion. I clearly stated that I would like to know if there is a standardized file extension for this kind of scripts. This question is even less opinion-based than this well received question on a similar issue (Use .sh or .bash extension for bash scripts?).
An official standard / convention for a file extension for shell scripts to source
SUSv2 SUSv3 POSIX 2008
I am looking for official documents on all POSIX standards and specifications. I would like to be able t read the docs to get a better understanding of UNIX systems and how they work at a low level. I've seen links here and there to opengroup.org, which I'm assuming is the entity behind the standards (however, I've heard IEEE mentioned a lot too). For a good rundown of POSIX, see this question: What exactly is POSIX? It answered a lot of questions for me.
Where can I find official POSIX and UNIX documentation?
There are at least 4 relevant pieces of text in the POSIX.2018 specification of awk: Emphasis (bold text) is mine in all the quoted text below:Input files to the awk program from any of the following sources shall be text filesThat means that if the input contains NUL characters (which would make it non-text as per the POSIX definition of text), then the behaviour is unspecified.\ddd : A <backslash> character followed by the longest sequence of one, two, or three octal-digit characters (01234567). If all of the digits are 0 (that is, representation of the NUL character), the behavior is undefined.So \000 results in undefined behaviour. About regexp matching:However, in all awk ERE matching, the use of one or more NUL characters in the pattern, input record, or text string produces undefined resultsAbout printf/sprintf:7.For the c conversion specifier character: if the argument has a numeric value, the character whose encoding is that value shall be output. If the value is zero or is not the encoding of any character in the character set, the behavior is undefined.So, that's another way to get a NUL character that leads to undefined behaviour. So, to sum up, in awk, POSIX tells us you can't use the NUL character portably, whether it's for input, output or to store in its variables. gawk (since at least 2.10 in 1989 which is the earliest version I could find where NUL support is documented) and @ThomasDickey's mawk (since version 20140914) are two implementations that can deal with NUL.
Is it legal to print null bytes using awk's printf function according to POSIX? The POSIX standard of awk does not seem to explicitly mention it either way. Real world implementations differ in how they behave: +$ gawk 'BEGIN { x = sprintf("\000"); print(length(x)); }' 1 +$ busybox awk 'BEGIN { x = sprintf("\000"); print(length(x)); }' 0 +$and +$ gawk 'BEGIN { printf("\000"); }' | xxd 00000000: 00 . +$ busybox awk 'BEGIN { printf("\000"); }' | xxd +$Is this specified somewhere in the standard? If yes, is the behaviour required for variables (x = sprintf("\000")) and printf (printf("\000")) same?
What is POSIX awk's stance on null byte in variables/printf?
Adapted from the POSIX standard's "Utility Argument Syntax" section: utility_name [-a] [-b] [-c option_argument] [-d|-e] [-f[option_argument]] [operand...]The utility in the example is named utility_name. It is followed by options, option-arguments, and operands. The arguments that consist of - characters and single letters or digits, such as a, are known as options (or, historically, flags). Certain options are followed by an option-argument, as shown with [-c option_argument]. The arguments following the last options and option-arguments are named operands. The standard also defines "argument" asIn the shell command language, a parameter passed to a utility as the equivalent of a single string in the argv array created by one of the exec functions. An argument is one of the options, option-arguments, or operands following the command name.All things after the utility_name on the command line are the utility's arguments, and they all show up in the positional parameters if it's a shell script. The terms option, option-argument, and operand are more specific names for these arguments on the command line. "Flag" and "switch" are common synonyms to "option". In the case of utility -a b=c-a and b=c are arguments, -a is an option if the utility recognises it as such (the ln utility has no -x option, so -x is not an option to ln, strictly speaking, and ln -x would trigger a diagnostic message), b=c is an option-argument if the -a option takes an argument, otherwise it's an operand, b and c are not options, option-arguments and not operands in themselves.As you notice from my text above, working from the synopsis of a utility (as given by the manual of the utility) would have been easier than trying to decode a generic command typed on the command line. The manual will clearly state what options takes option-arguments and what arguments are operands etc. To call c a "value" is IMHO perfectly ok. It's not a something that is standardised, but very few would misunderstand you if you say "c is the value given to b". It would be clear from the context of the utility in question. For example $ awk -v var="d" '...' data.inAnyone who knows about awk would say that -v var="d" means "the awk variable var is assigned the value d on the command line".
I came across a confusing variation in the understanding what options and arguments are with regard to the syntax of commands. For instance, I encountered definitions like:command -a -b -c d e f some differ between -a -b -c, call them options or switches and d e f by calling them arguments. command -a -b -c d e f some, for instance a bash manual, call all -a -b -c d e f arguments and explains, that all of them are accessible from a script by $1 $2 $3 $4 $5 $6 respectively. command -a b=c some call -a an option, b an argument and c the value, but others mix them like in the first two points, in one variety calling all -a b c arguments.Those three versions are only examples for a plethora of different calling varieties, I do not even know how to list them all, but I noticed that for sure there is no fixed naming convention. Or at least, there is no standardised naming convention I know about, because I came across different random sources, but even among official Linux and GNU affiliated sites or manuals I could met this inconsistency. Is there a unquestionable official naming scheme I can refer to?
Confusion about changing meaning of arguments and options, is there an official standard definition?
Yes and no. In a POSIX environment, the utilities must behave as described by the specification. In practice, this means that conforming versions of the utilities must be present in $PATH. However, when running your program on a POSIX-compliant system, you may be running it in a non-conforming environment. In practice, what often happens is that the OS has a legacy mode and a POSIX mode, and is in the legacy mode by default. Worse than missing some commands, the legacy mode tends to have incompatibilities in them, such as options with different meanings. You can retrieve a good PATH with getconf. Of course, it's tricky, as getconf in the original $PATH may not be the right one. The Application Usage for command shows a way to do it: command -p getconf PATHAs far as I understand the specification, this is not necessary if you are running your program in a POSIX-conforming environment; and if you aren't running your program in a POSIX-conforming environment, POSIX doesn't apply. However, this application usage can be taken as a recommendation: if this doesn't work, you can feel entitled to complain to your vendor that whatever they are doing regarding the letter of the POSIX spec, they are not complying with its spirit.
In the "Command Search and Execution" section, the POSIX specification says that PATH is searched when finding a utility to execute (with some exceptions). Does the specification mention anywhere that PATH will be initialized to a value that guarantees that all standard utilities will be found? Or do I need to do something like the following to guarantee that I'll never get a "command not found" error when trying to run a standard utility? PATH=$(command -p sh -c 'printf %s "${PATH}"')(see the POSIX specification of the command utility)
Does POSIX guarantee that the standard utilities are in PATH?
It seems that they are standardized in the POSIX spec,POSIX.1-2017 by proxy of unistd.hThe header shall define the following symbolic constants for file streams:STDERR_FILENO File number of stderr; 2. STDIN_FILENO File number of stdin; 0. STDOUT_FILENO File number of stdout; 1.But also the POSIX docs on "stderr, stdin, stdout - standard I/O streams" state,This volume of POSIX.1-2017 defers to the ISO C standard.The ISO ISO/IEC 9899:201x Standard state only,The three predefined streams stdin, stdout, and stderr are unoriented at program startup.It seems ISO C is relatively mute on this allowing the kernel to assign whatever it wants to the descriptors known as STDOUT, STDERR, and STDIN. But that the POSIX docs on unistd.h are explicit about what they should resolve to at that level. Other Operating SystemsMicrosoft Windows follows the POISX convention in the "Low Level I/O" interface
Does POSIX mandate that stdin is 0, stdout is 1 and stderr is 2 or is this only a convention? Do other systems diverge from that convention or is it a safe assumption?
Does POSIX standardize the file descriptor numbers?
Quoting from the Single Unix specification version 2, volume ”Commands & Utilities", §2.13.3:If a filename begins with a period (.) the period must be explicitly matched by using a period as the first character of the pattern or immediately following a slash character. (…) It is unspecified whether an explicit period in a bracket expression matching list, such as [.abc] can match a leading period in a filename.There is no exception that would make the second period in .., or the empty string following the only period in ., not matched by the wildcard in .*. Therefore the standard says that .* matches . and .., annoying though it may be. The passage above describes the behavior of the shell (sh command). The section on the glob C library function refererences this passage. The language is exactly the same in version 3, also known as POSIX:2001 and IEEE1003.1-2001, which is what most current systems implement. Dash, bash and ksh93 comply with POSIX. Pdksh and zsh (even under emulate sh) don't. In ksh, you can make .* skip . and .. by setting FIGNORE='.?(.)', but this has the side effect of making * include dot files. Or you can set FIGNORE='.*', but then .* doesn't match anything. In bash, you can make .* skip . and .. by setting GLOBIGNORE='.:..', but this has the side effect of making * include dot files. Or you can set GLOBIGNORE='.*', but then .* doesn't match anything.
Is the behavior of .* to include . and .. defined in LSB or POSIX or some other specification?
Is the behaviour of .* to include . and .. defined in LSB or POSIX or some other specification?
In the 21st century, especially if you're targeting machines that are likely to have bash or zsh, you can count on type being available. (It didn't exist in extremely old unices, as in, from the 1970s or early 1980s.) You can't count on its output meaning anything, but you can count on its returning 0 if there is a command by that name and nonzero otherwise. which isn't standard and is unreliable in practice. type is the recommended alternative. whereis suffers from the same problems as which and is less common. whence is specific to ksh and zsh. When that's possible, it would be more reliable to test the existence of a command and test whether its behavior looks reasonable. For example, test the presence of a suitable version of bash by running bash -c 'somecommand', e.g. # Test for the `-v` operator (which appeared in bash 4.2) if bash -c 'test -v HOME' 2>/dev/null; then …Today you can count on almost everything in the Singe UNIX specification version 2 (except for exotic stuff like Fortran and SCCS, which are optional anyway). You can count on most of version 3, too, but this isn't completely implemented everywhere yet. Version 4 support is sketchier. If you're going to read these specs, I recommend reading version 3, which is a lot more readable and less ambiguous than version 2. For examples as to how to detect system specificities, look at autoconf and at configure scripts of various software. See also Resources for portable shell programming for more tips.
I've been frustrated before with differences in output from the which command across different platforms (Linux vs. Solaris vx. OS X), with different shells possibly playing into the matter as well. type has been suggested as a better alternative, but how portable would that be? In the past I've written functions which parse the output of which and handle the different use cases I've run into. They work across the machines I use, and so are okay for my personal scripts, but this seems terribly unreliable for software that I'm going to post somewhere for others to use. To take just one possible example, suppose I have to detect from a script whether bash and zsh are available on a machine, and then run a command with zsh if it is present, and with bash if zsh is not and bash is of a sufficient version to not have a particular bug. Most of the rest of the script could be Bourne shell or Ruby or anything else, but this one particular thing must be done (AFAIK) with either zsh or a recent version of bash. Can I count on type being available across platforms? Is there some other alternative to which which can easily and consistently answer the question of whether a particular piece of software is installed? (If you want to also give ideas specifically related to the example I gave, that's great, but I'm mainly just asking about the general case: what is the most reliable way to find out if a particular thing is installed on a given machine?)
What is the best way to detect (from a script) whether software is installed?
Greg's Wiki has a post on adapting bash scripts for Dash that points out a lot of 'bashisms' - extra features that are non-standard but are a part of bash. Avoiding those bashisms can help to make your script friendlier to different environments. This particularly answers some of your questions. For instance, yes, there are operators that differ (like ==), but there are a standard Posix set that should work in all environments. For more thorough reading, you can check out the Posix standard, which all shells should comply to. Particularly, the volume on "Shell & Utilities". What I find more challenging than the shell differences are the command differences. Many Linux systems have GNU find, but if you're writing a portable script, don't rely on your own man find, because there are lots of systems out there with BSD find, which has a different feature set. If you're writing scripts for busybox, you'll find there are different versions with entirely different ncs. Those are the kinds of things that always get me when I deploy a script to different environments. For extra reading on good shell scripting practices, there is also a good resource on David Pashley's blog: Writing Robust Bash Shell Scripts Also, make sure you read Gilles answers and comments on this site. He has lots of tips about making sure you use portable code.
Under some answers, I see comments that recommend avoiding shell specific commands in answers. How do I know which commands, operators, etc exist in all shells? Is there a list of standards?man builtins gives a list of commands. Are those the only commands that I can use in a portable shell script that works in all shells? Can a built-in be shell specific? Do the standards for Linux differ from that of other Unixes? What about syntax? Can punctuation, operators, etc be different in some shells?
What is not shell specific?
The actual behavior is defined by the spec entitled the Inter-Client Communication Conventions Manual (ICCM). Basically the class name is specified by the person who makes the app. The instance name can be specified by the user and its specified resources should override the class name specified resources. Here is what ICCMv2 for X11r6 says on WM_CLASS,4.1.2.5. WM_CLASS Property The WM_CLASS property (of type STRING without control characters) contains two consecutive null-terminated strings. These specify the Instance and Class names to be used by both the client and the window manager for looking up resources for the application or as identifying information. This property must be present when the window leaves the Withdrawn state and may be changed only while the window is in the Withdrawn state. Window managers may examine the property only when they start up and when the window leaves the Withdrawn state, but there should be no need for a client to change its state dynamically. The two strings, respectively, are:A string that names the particular instance of the application to which the client that owns this window belongs. Resources that are specified by instance name override any resources that are specified by class name. Instance names can be specified by the user in an operating-system specific manner. On POSIX-conformant systems, the following conventions are used:If -name NAME is given on the command line, NAME is used as the instance name. Otherwise, if the environment variable RESOURCE_NAME is set, its value will be used as the instance name. Otherwise, the trailing part of the name used to invoke the program (argv[0] stripped of any directory names) is used as the instance name.A string that names the general class of applications to which the client that owns this window belongs. Resources that are specified by class apply to all applications that have the same class name. Class names are specified by the application writer. Examples of commonly used class names include: "Emacs", "XTerm", "XClock", "XLoad", and so on.Note that WM_CLASS strings are null-terminated and, thus, differ from the general conventions that STRING properties are null-separated. This inconsistency is necessary for backwards compatibility.(emphasis in bold added by me)
When I run xprop I get a class string that has two values, one of them i3 calls an instance, the other a class, for example on chromium-browser the xprop utility will return something like this, WM_CLASS(STRING) = "chromium-browser", "Chromium-browser"What is the official guidance on a window and these two fields? For this they're pretty similar. Are they ever different? If so, what should I pick and why? How are GUI-authors supposed to class and instance their names?
WM_CLASS vs WM_INSTANCE?
According to the POSIX specification:The system may provide non-standard extensions. These are features not required by POSIX.1-2008 and may include, but are not limited to:--snip--Non-conforming file systems (for example, legacy file systems for which _POSIX_NO_TRUNC is false, case-insensitive file systems, or network file systems)--snip-- So it looks like case sensitivity is the norm, but it is possible to support a non-compliant (case-insensitive) file system and still call your product UNIX as long as it can also support case-sensitive file systems. (edit) Actually, see this part of the specification:Two proposals were entertained regarding case folding in filenames:Remove all wording that previously permitted case folding.Rationale Case folding is inconsistent with the portable filename character set and filename definitions (all bytes except <slash> and null). No known implementations allowing all bytes except <slash> and null also do case folding.Change "though this practice is not recommended:" to "although this practice is strongly discouraged."Rationale If case folding must be included in POSIX.1, the wording should be stronger to discourage the practice. The consensus selected the first proposal. Otherwise, a conforming application would have to assume that case folding would occur when it was not wanted, but that it would not occur when it was wanted.So it looks like is purposely left ambiguous - it is neither explicitly permitted nor forbidden.
One answer to this question mentions the UNIX 03 certification of OSX. Now AFAIK the standard file system of OSX is/was HFS, which "saves the case of a file that is created or renamed but is case-insensitive in operation" (i.e. it's case-preserving but case-insensitive). Does the UNIX certification or POSIX require a case-sensitive file system?
Does the UNIX standard require case-sensitive filesystems?
POSIX doesn’t have much to say about the administrative user; when privileges are discussed, they are discussed in terms of process privileges (since that’s what really matters in POSIX-style systems). It acknowledges the existence of the root user but doesn’t define any requirements on its home directory. The FHS explicitly marks /root as optional, sayingThe root account's home directory may be determined by developer or local preference, but this is the recommended default location.It’s worth considering that root’s home is somewhat special, in that it makes life easier if it is accessible and on a volume with some available space when root needs to log in, or if it doesn’t block unmount operations on anything other than the root volume; this is why it is traditionally on the root volume, and not on user home directory volume(s) when the latter are separate from /. But that’s just a practical consideration, not a requirement in any widely-acknowledged standard I’m aware of. The flip side of the coin is that many operating environments no longer have a root home directory at all (and not just in containers).
I moved /root to /home/root and changed the appropriate entry in /etc/passwd in my Linux system quite some time ago and everything's worked until recently when I discovered that at least the firejail application hardcodes the root home directory and stops working otherwise under some circumstances. I presume it will be patched eventually but still. I wonder if the root user home directory in Linux must be in /root, or it's still movable just like home directories of other users. Is there anything in POSIX which standardizes this? What about other Unixes?
Is /root a hard requirement for a modern Linux system? What about POSIX? UNIX?
Can someone confirm (or deny) my assumption?Yes, Both are same. UNIX mbox format is used by AsyncOS when messages are archived (in anti-spam and anti-virus configuration) and logged (in the message filter log() action). mbox is traditional UNIX mailbox format. Users' INBOX mboxes are commonly stored in /var/spool/mail or /var/mail directory. Single file contains multiple messages and is the most common format for storing email messages on a hard drive. All the messages for each mailbox are stored as a single, long, text file in a string of concatenated e-mail messages, starting with the “From” header of the message.
man git-format-patch makes reference of the UNIX mailbox format which is a term I am unfamiliar with. A google search for "UNIX mailbox format" and similar expressions lists many hits with the term mbox in it. There is even a man page (man mbox) for mbox. I am lead to conclude that mbox and the UNIX mailbox format are the same thing, but I am not 100% sure. Can someone confirm (or deny) my assumption?
What is the unix mailbox format?
The LSB, POSIX, and the Single UNIX Specification all significantly involve userland. Simply using a kernel that is also used as the basis of a "unix-like", "mostly POSIX compliant" operating system -- GNU/Linux -- is not sufficient to make Android such as well. There are, however, some *nix-ish elements, such as the shell, which is a "largely compatible" Korn shell implementation (on pre-4.0, it may actually be the ash shell, which is used on embedded GNU/Linux systems via busybox) and various POSIX-y command line utilities to go along with it. There is not the complete set most people would recognize from the "unix-like" world, however.is it close enough to be compliant with the Linux Standard Base? A centrepiece of the LSB is the filesystem hierarchy, and Android does not use this. LSB really adds stuff to POSIX, and since Android is not nearly that, it is even further from being LSB compliant. This is pretty explicitly not a goal for the platform, I believe. The linux kernel was used for its own properties, and not because it could be used as the core of a POSIX system; it was taken up by GNU originally for both reasons. To clarify this distinction regarding a user space oriented specification -- such as POSIX, Unix, or the LSB extensions -- consider some of the things POSIX has to say about the native C library. This is where we run into platform specific things such as networking and most system calls, such as read() -- read() isn't, in fact, standard C. It's a Unix thing, historically. POSIX does define these as interfaces but they are implemented in the userland C library, then everything else uses this library as its foundation. The C library on GNU/Linux is the GNU C Library, a completely separate work from the kernel. Although these two things work together as the core of the OS, none of the standards under discussion here say anything about how this must happen, and so in effect, they don't say anything about what the kernel is or must do. They say a lot of things about what the C library is and must do, meaning, if you wrote a C library to work with a given kernel -- any kernel, regardless of form or characteristics -- and that library provides a user land API that satisfies the POSIX spec, you have a POSIX compliant OS. LSB does, I think, have some things to say about /proc, which linux provides as a kernel interface. However, the fact that this (for example) is provided directly by the kernel does not mean that the LSB says it has to be -- it just says this should/could be available, and if so what the nature of the information is.
Moved from Stack Overflow, where I realize it was off-topic since it was asking for sources - far as I can tell, the rules forbid that there but not here. I know that the kernel in Android is now mostly the Linux kernel with a few exceptions like wakelocks (as described by John Stultz.) But is it close enough to be compliant with the Linux Standard Base? (Or for that matter with POSIX and/or the Single Unix Specification?) I'm writing about this in an academic term paper, so as well as the answer itself it would be great to have a relatively reliable source I can cite for it: a peer-reviewed article or book would be ideal, but something from Google's developer docs or a person with established cred (Torvalds, Andrew Josey, etc.) would be fine.
Is Android compatible with the Linux Standard Base?
The 3pm section is not used anymore. It is defined as manual pages concerning modul packages of perl in an old version of the Debian Perl Policy, noteably in version 1.2. Here is a site where you can read that old deprecated policy (see §3.1 and §1.4). In the latest Debian Perl Policy it is defined in §2.4 that module manual pages should be installed in section 3perl now. In the standards manual page you see that "POSIX.1-2001, SUSv3" standard has defined manual page sections called 1p and 3p. That is also mentioned at Wikipedia, that p is a subsection that describes POSIX specifications. 3p is also an abbreviation of 3posix, which means the same. The sections n and l seem to appear only in IBMs AIX. n specifies "new" and l specifies "local". Local (l) manual pages describe usage policies, administrative contacts, special local software, and other information unique to this particular installation. New (n) manual pages are for newly installed software. They stay for an amount of time in n before they get moved to their permanent section. In Linux those two section and also the o section (old) are deprecated. Note, that n in Mac OSX can also be the section for Tcl/Tk functions.
An excerpt from the man man page:The default action is to search in all of the available sections following a pre-defined order ("1 n l 8 3 2 3posix 3pm 3perl 5 4 9 6 7" by default)What are the n, l and 3pm sections of the manual for?
What are the 'n', 'l', '3pm' sections of the manual for?
LSB specifies some group names, but users is not one of them. http://refspecs.linux-foundation.org/LSB_5.0.0/LSB-Core-generic/LSB-Core-generic/usernames.html On a completely new setup, you might prefer to avoid using 1000. The way useradd works, it would allocate each user a group, and the numeric identifiers for user and group id will conveniently end up the same. I would call that the preferred approach for modern multi-user systems (I think older systems defaulted to a shared group like users as the primary group of the user instead). My users are not necessarily a member of a shared group like this on either Fedora or Debian. In this case it would be somewhat academic what number is assigned - it would just be another system group which varies between different distributions. (And another group like bin with no apparent purpose in modern times). LSB says that UIDs and GIDs 0-99 are statically allocated by the system. UIDs 100-499 (and on all modern systems 100-999) are supposed to be allocated dynamically. This is confirmed by the Debian Policy Manual; it just doesn't have the virtue of being strictly true at the current time. I'm not really sure what it means that I see users as 100 on a Debian system. It might not be a safe assumption to make, in case the order the groups are allocated in changes for some reason. On Fedora, it's pretty safe to assume you can allocate id 100, because the automatic allocation of id's 100-1000 actually counts down. (To be clear, this is the opposite of Debian). Possible options considering your information so far:Stop using the group users. But probably you have some shared files and you'll need to allocate a shared group ID anyway. Use 100 and hope it doesn't break if you [re]install a system that allocates system IDs counting up from 100 like Debian. Use something high enough like 10000, which would never end up allocated automatically. Use 1000 if none of your existing systems use it for something else and you never plan on adding a new OS which accesses your filesystems.[*] Allocate a free ID towards the start of the range 500-1000. (Fedora over five years ago, counted down from 499-100 instead of 999-100, so I can't exclude that you have allocations like that).[*] Once a system is installed, you can add users with any IDs you want. But my worry is that the initial user created by an OS installer is likely to have ID & GID 1000, not allow you to change them, and particularly if it doesn't create a root user then changing its ID later can be quite annoying). The 10000 option sounds simplest to me. It would work nicely if you were ever creating a new system, or instructing someone else. It should also work on your current system.
I have several GNU/Linux installations that share home and data directories. Over time some user files in these directories have received the group ID 100 (users group under some variants of Linux), others have the group ID 1000 (also the users group, under other variants). Now I wish to unify the users group ID between all my distributions, but which one should I choose? I remember there is a Linux standard, does that give a recommended GID for users? If not, is there any other recommendation or trend (I am not asking about personal preferences)?
Recommended GID for users group in Linux (100 or 1000)?
Arch is a minimalistic linux distribution, so normally there are no other special configuration files which are getting included in some strange placces, modified by system configuration wizards. /etc/profile is the right place to do this for a system wide configuration.This file is intended to be used for ALL common Bourne-compatible shells. Shell specifics should be handled in /etc/profile.$SHELL where $SHELL is the name of the binary being run (discounting symlinks)It is also mentioned in the official FAQ for reloading if your shell can't find a newly installed binary
Is there a standard for $PATH and the order of things that are supposed to be in there? out of the box Arch Linux doesn't have /usr/local/bin in the $PATH. I want to add it but I'm not sure if there's a predefined pecking order for system paths. Also where is the right place to do this? for right now I modified /etc/profile but I'm not sure that's the right place in Arch for user modifications. Anyone know if there's a better place?
modify path globally
This is not distro specific so much as Desktop Environment or Window Manager specific. First of all, there is the situation of users logging into a text console or remote tty via ssh. What gets run when those users login is usually controlled by their shells rc files and the system shell profiles. Then there is the graphical environment case, which is probably what you are mostly after. Those depend very much on the environment. Gnome has a session manager that handles launching things on login. I assume KDE has something similar. Other window managers have their own mechanisms, usually starting with some kind of hook in their config files. It is also possible to build your own environment with a script that acts as the login shell that gets run after authenticating, then does whatever background work you want, then fires off a window manager or DE. Basically, there is no one way. You need to know something about your target environment.
Is there a standard way to make a program start when a user logs in? On Ubuntu, for example, you can place a .desktop file in ~/.config/autostart and the application will launch on startup. Does this apply to other distros as well?
Is there a standard way to have a program start when a user logs in on Linux?
I found this paragraph in a withdrawal letter for FIPS which might be why it was withdrawn: excerpt from withdrawal letterIt is no longer necessary for the government to mandate standards that duplicate industry standards. Federal government departments and agencies are directed by the National Technology Transfer and Advancement Act of 1995 (P.L. 104-113), to use technical industry standards that are developed in voluntary consensus standards bodies.There is also this letter/email: From: "richard l. hogan" <Richard=L.=Hogan%dpi%[emailprotected]> Date: Tue, 29 Oct 96 9:20:26 CST Subject: Withdrawal of FIPSWhich discusses that the NIST and the Dept. of Commerce were dropping national designations for things such as ANSI 3.64 when they already had a international designation (ISO). excerpt from that letter/emailOne of the pieces of legislation that, according to NIST and the Department of Commerce, enabled the FIPS program was rescinded this year. The law - sometimes referred to as the Brooks Act - contained specific requirements for establishing uniform standards for information processing in the Federal government and for making those standards mandatory in Federal procurement actions. OMB Circular A-119 further clarified that mandatory Federal standards took precedence over voluntary national and international standards. Now, as a result of treaty negotiations making the Untied States part of the World Trade Organization, the Books Act has been replaced with new legislation that requires Federal agencies to consider voluntary international and national standards FIRST in procurement actions and to cite Federal standards only when no appropriate international or national standards exist. In many cases FIPS have international (ISO) or national (ANSI) standard equivalents. For example, FIPS 123 (Data Descriptive Format for Information Interchange) is also ISO-8211. The change in legislation requires Federal procurements to now cite ISO-8211. Previously, we were required to cite FIPS- 123. As a result of this change, NIST has recognized an opportunity to make government "work better and cost less" by withdrawing any FIPS that already has an equivalent ANSI or ISO specification or any FIPS that is not mandatory; i.e., is just a guideline. What remains on the "active" FIPS list are mandatory Federal standards which currently have no ANSI or ISO equivalent; for example, the Spatial Data Transfer Standard (FIPS 173-1) and the Government Information Locator Service (FIPS 192). NIST is not withdrawing important standards like Pascal, FIPS 109; SGML, FIPS 152; or Hydrologic Unit Codes, FIPS 103. The proper way to look at this action is that NIST is withdrawing the Federal designation of these standards in favor or their national or international standards designations; ANSI X3.97-1993 for FIPS 103, ISO 8879 for FIPS 152, and ANSI X3.145-1986 for FIPS 103. From a user point of view, this action by NIST is nothing more than a way to assure the designation change required by the new legislation.I would interpret this as follows: Since ECMA-48 already covered the standard at an international level there was no need to create redundant standards within ANSI.
From the Wikipedia "ANSI escape code" article:The name "ANSI escape sequence" dates from 1981 when ANSI adopted ECMA-48 as the standard ANSI X3.64 (and later, in 1997, withdrew it).Does anybody know why the standard has been withdrawn. I tried to follow the link in the article but didn't find anything.
Why has the ANSI 3.64 standard been withdrawn?
(Copied from my comment on the question, as requested.) See Why should files end with a newline? - Stack Overflow. The "TL;DR": POSIX says so, and it's pretty logical to have a line end in and end-of-line character. See the linked Stack Overflow question for practical consequences.
Possible Duplicate: What's the point in adding a new line to the end of a file? What is considered better behaviour: to leave the last letter of the last line to be the last byte of a file, or to press Enter at the end to let there be a lf? Why?
Should I end my text/script files with a newline? [duplicate]
Usually just the name of the package or program, so hadoop in this case. Daemons are usually added as a system account using useradd -r, which gives them a userid lower than human users (on my system, system accounts start at 100, human users start at 1000). Looking at the user names for system accounts in /etc/passwd seems to confirm the lack of any service, daemon, or d convention, e.g. dnsmasq pulse ntp sshdetc. are all accounts for system daemons.
I'm from a windows background where I'm used to creating separate domain service accounts for running various services. I like to keep things need so I would name them DOMAIN\service.whatever I'm about to create a daemon account for running hadoop on Centos linux, I'm just playing around on a home VM but would like to know if there is a commonly used naming convention for linux in industry? e.g. hadoop.daemon or hadoop.d or dhadoop or hadoopd (the letter d seems to be used everywhere else in the unix world for service daemon stuff...) Thanks!
Is there a common naming convention for daemon user accounts?
If my goal is to write a script for POSIX compatible shells, scripts that I would begin with #!/bin/sh, how permissible is this [[ syntax.Not at all. Many modern Linux-based systems use dash as /bin/sh by default, which is fully POSIX-compliant and no more, and so [[ will not work. This includes every recent Debian and Ubuntu release, and their derivatives, as well as many other distributions. Historically these systems commonly used Bash there instead, and deliberately switched to improve performance. Many other systems, including most of the BSDs and most commercial Unices, don't support [[ either and never have: their sh is POSIX-only, or its extensions don't include the [[ syntax. OpenBSD's sh does support a version of [[, which is slightly different than Bash's; I don't know of any others that do, although they may exist. Otherwise, it's only systems that use Bash as /bin/sh (or less often zsh, or even less often some others) where [[ will work in something declared to be a sh script.On the other hand, the large majority of systems have Bash installed in practice, and just making your script explicitly be run with bash will suffice for all of them. Bash's sh-emulation mode has always been broken anyway. Since you're relying on Bash features, I can't see any reason at all you'd want to declare it as a sh script: just say #!/bin/bash and be done, using [[ as much as you want — or even better, to the total exclusion of [. If you instead want maximum portability, use [ or test and POSIX sh1, and write carefully. 1Note that some of the commercial Unices have, or have had, non-POSIX sh as /bin/sh; to work uniformly on those you'll need to run the scripts with the full path to the system's POSIX sh.
I have found some very good answers here on the differences between [ and [[ in 'if' statements. For specific named shells, it seems to be a good idea to use [[ over [ (and it is faster, too). I'm still unclear on portability, however. If my goal is to write a script for POSIX compatible shells, scripts that I would begin with #!/bin/sh, how permissible is this syntax. From what I've read, double brackets are not in the POSIX standard, but in the "real world" how much of an issue is this really? I suppose what I mean is that I want a portable script, but it is good enough for it to work on all viable POSIX shells post, say, 2000-2005. Meaning, it's not part of the standard, true, but realistically any shell from 2005 onward is almost certain to accept the syntax. Also, a more general question concerning script portability and POSIX: how do other authors handle this? I understand use cases and target audience govern much of the decision, but do you try to stick as close to POSIX as possible to cut down on possible incompatibilities from the Internet at large, or do you avail yourself of all the nice things that most shells support that have yet to make it anywhere near a POSIX standard? I began by trying to make most of my scripts as Bourne and POSIX compliant as possible. Over time, though, from reading more of the Bash documentation and from seeing other people's scripts on the Net, I have to say that making use of these other features can make for scripts that are much easier to read and in many cases much smaller.
Single or double brackets and portability
this command did the job printf '\x0f\x11' | program
I've got a program that requires some unprintable characters like 0x0F (ctrl+o) as input to execute the intended part of the program. 0 000 00 NUL &#000; Null char 1 001 01 SOH &#001; Start of Heading 2 002 02 STX &#002; Start of Text 3 003 03 ETX &#003; End of Text 4 004 04 EOT &#004; End of And it is being executed on command line, any idea how to insert unprintable chars to command line as input of a program?
Unprintable characters as input in command line
This can be helpful (for tar but I think it can be extended to other programs as well): https://www.gnu.org/software/tar/manual/html_section/tar_21.htmlLong options are meant to be obvious and easy to remember, and their meanings are generally easier to discern than those of their corresponding short options (see below). For example: $ tar --create --verbose --blocking-factor=20 --file=/dev/rmt0 gives a fairly good set of hints about what the command does, even for those not fully acquainted with tar.Also this link Standards for Command Line Interfaces. And here is a joke about GNU long options: https://www.gnu.org/fun/jokes/long-options.en.html Usually running command -h/--help shows which options (short/long) the command provides.
In most scripts (but mainly bash) it's commonplace to see some arguments that are configured like so: bash-4.3:$ command --longer-argument -la Where did this originate from? I'm mainly just curious as to why this became effectively a unanimous standard. Is it mainly for readability? Also, why not use something like bash-4.3:$ command -longer-argument, where all CLI arguments are specified by only one dash?
bash: --argument vs -arg [duplicate]
To do this, you can use the mailx command. Below is an usage example: mailx -v -s "Subject" -S smtp-use-starttls -S ssl-verify=ignore -S smtp-auth=login -S smtp=smtp://<server_name>:25 -S from="[emailprotected]" -S smtp-auth-user=<username> \ -S smtp-auth-password=<password> [emailprotected]This example is using SSL and SMTP authentication.
What is the most portable or standard way to send an email from the console or a script on Linux, and possibly Unix?
Standard and portable way to send email from console?
Search the web for "sun application porting assistant 1.0 final release". I believe it is still downloadable from Oracle web site: It is a static source code analysis and code scanning tool that can be used to identify incompatible APIs between the Linux and Solaris platforms. Sun Application Porting Assistant's robust C/C++ and shell script parsers are able to examine these source files with reasonable accuracy and produce reports that can be used in porting the application. Together with an easy-to-use GUI and a simple command-line interface, Sun APA is intended to simplify and speed up estimation and porting times.
I've developed a few Bash scripts on a LFS system which should now be made to work on a minimal installation of Sun Solaris 10. Is there a guide somewhere with at least some general tips for conversion, and even better, a "conversion table" for common commands and options? This answer would be a good example of a single entry in such a table.
Shell scripts Linux -> Solaris conversion guide
The TIS/ELF one covers ELF in general, while the System V ABI is a supplement which documents the x86_64 Application Binary Interface. The second document does not contain any information about x86_64 since the architecture didn't exist at the time it was written.
There are at least two standards of Executable and Linkable Format (ELF), one of themSystem V Application Binary Interface AMD64 Architecture Processor Supplement (With LP64 and ILP32 Programming Models) Version 1.0 Tool Interface Standard (TIS) Executable and Linking Format (ELF) Specification Version 1.2The older one, the TIS ELF Standard 1.2 is 106 pages while the SysV ABI is 157 pages but covers ELF only on pages 63-86 (23 pages). How do these two standards relate to each other? And which one does Linux and GNU Linker use? What is the Tool Interface Standard?
Different standards of ELF (SysV vs TIS) and Linux?
My gut feeling is that I should split on spaces and execute.Good instincts. You're calling exec(3); it's up to you how to interpret the environment variables you support. By supporting options, you save the user the trouble of writing a script to tuck them into a single $PAGER name. A good example to follow might be man(1). On my system, it supports MANPAGER, which says, If MANPAGER is set, its value is used as the name of the program to use to display the man page. If not, then PAGER is used. If that has no value either, /usr/bin/less -is is used.That at least implies that PAGER can contain options. You might experiment with yours to see. I bet it does. I don't think Posix addresses the question of how environment variables that denote utilities are interpreted. I think the best you have is common examples of prior art. As to whether or not to pass it though "the" shell, I'd say No, unless you want to take advantage of shell variable expansion, and document it. It's simpler and more predictable to keep the shell out of it.
I'm writing an application from which I want to run a user-specified pager. The standard way to do this seems to be to look at the PAGER environment variable. I'm unclear as to whether this is a program name or a program name together with arguments. I tried to find standards mentioning this, but could not. My gut feeling is that I should split on spaces and execute. Am I correct? I have come across various programs that assume environment variables like $PAGER and $EDITOR are program names without environment variables. Perhaps I should execute with sh instead though? LinksThis question discusses the source of various common environment variable
Can $PAGER contain spaces?
nothing is guaranteed. root - is usually on linux/unix systems, but - i saw systems where uid=0 was used by "admin". Usually - there are users like root, nobody, daemon, bin, sys. www-data is on debian/ubuntu, but for example on redhat/centos/fedora/pld there is apache user instead. Recomendations/fixed uids for users other than root are only within distribution. The same is with uids of regular users - sometimes they start from 100, sometimes from 500, sometimes from 1000...
Beside the root (which I guess IS guaranteed), is there any other username guaranteed to exist on Unix system? Linux system? Fixed UIDs for those users? If not guaraneed, are there at least any recommendations? My sampling of several Linux distros showed that users such as 'bin', 'daemon', 'sys', 'www-data' and 'nobody' were present, though UIDs differed a bit so that appears to be 'no' on the UID question...
Are there any user guaranteed to exist on the system
In this context, a “stream” is an open file in a process. (The word “stream” can have other meanings that are off-topic here.) The three standard streams are the ones that are supposed to be already open when a program starts. File descriptor 0 is called standard input because that's where a program is supposed to read user input or its default data input. File descriptor 1 is called standard output because that's where a program is supposed to write its normal data output. File descriptor 2 is called standard error because that's where a program is supposed to write its error messages. Other file descriptor numbers are not standard anything because they don't have such a preassigned role. They'll end up being used for whatever the program wants. So could call any file opened by a program a “nonstandard stream”, but it would be weird and confusing: “open file other than stdin, stdout or stderr” doesn't really need a name, and “nonstandard stream” sounds like it's some special type of file or a file opened by a nonstandard method, which is not the case. The conventional role of file descriptors 0–2 is granted by the standard library and by certain programs. For example, console login programs and terminal emulators start the shell (or other program) with the terminal open on these file descriptors. The C standard library creates FILE* objects (what C calls streams) for these three standard descriptors. There's no special treatment in the kernel.
The so-called "standard streams" in Linux are stdin, stdout, and stderr. They must be called "standard" for a reason. Are there non-standard streams? Are those non-standard streams fundamentally treated differently by the kernel?
Are there "non-standard" streams in Linux/Unix?
From the chapter on "Scope":The Linux Standard Base (LSB) defines a system interface for compiled applications and a minimal environment for support of installation scripts. Its purpose is to enable a uniform industry standard environment for high-volume applications conforming to the LSB. [...] The LSB is primarily a binary interface definition. Not all of the source level APIs available to applications may be contained in this specification.For the things that the LSB does not define, such as most things relating to the behavior of standard utilities (except for certain extensions) and definitions of basic terms, it refers to the POSIX standard (which is a normative reference for the LSB, i.e. the LSB builds on top of POSIX). The POSIX standard tells us that a line isA sequence of zero or more non-<newline> characters plus a terminating <newline> character.This means that a line of text must be terminated by a newline character, even on a system conforming to the LSB 4.1 standard.
Both POSIX and SUS (Single UNIX Specification) define a line asA sequence of zero or more non-<newline> characters plus a terminating <newline> character.Many distributions are more oriented towards LSB than POSIX. LSB includes a lot of POSIX/SUS standards but not all exactly. Must lines also be terminated with a NEWLINE character in regards to LSB v4.1 ?
Is a NEWLINE character at line end required by LSB (Linux Standard Base)?
If you don't have utilities that can understand NUL characters, then this historical behavior can be used to distinguish between files. The output of find will never contain two slashes in a row unless they are provided as part of the initial path. This means that output like .//path/to/file ./name/moretells you that there is a directory called file\n. rather than there is a sub-directory of the current directory called name if you invoke find with find .// -print
Is it true that find is not supposed to be doing even the most simple path unification/simplifications operations, such as coalescing multiple successive slashes together (which would be equivalent to the original form)? For example the output of find ./// is: ./// .///somefile […](tested with find from GNU and busybox) If so then why is that? Is there any sensible use case I'm missing? Perhaps for the case that someone is grepping the output of find inside scripts? BTW, Also interesting is the output of GNU's find for find ./// -maxdepth 0 -printf '%h\n' (%h is supposed to be "Leading directories of file's name (all but the last element and the slash before it)"): .// (simply one fewer /)
Any reason why find does not merge multiple slashes into one?
I see that the LSB includes both Perl and Python...Python, at least, includes http tools in the standard library. I didn't investigate to see if the LSB mandates libwww-perl. If you don't want to write anything yourself and you're happy with output to stdout, you can do this: python -murllib http://example.com/And if you're feeling really motivated, you can write a simple http client in bash.
From what I can understand of LSB documentation, neither wget or netcat are standard tools always available in an LSB environment. Is there some other way to make a http request without being dependent on anything else than LSB? What would be the most safe tool to be dependent on if I want to make it as simple as possible for users of my tool?
bash script with network request in pure lsb environment
It's specified by the OpenGroup (the body specifying Unix) and by the Linux Standard Base. I don't know how well those are followed on the various Unices/Linuces though. The Wikipedia page is also a good reference.
Related to a StackOverflow question I have. Since it's more or less really a SO question through and through, I won't go into the whole spiel. My platform question is this: Is there an industry standard somewhere that specifies how various aspects of PAM should operate?
Is there a PAM Standard?
Here it is: The FHS 2.3 Specification
Possible Duplicate: Resources to learn linux architecture in detail? I migrated to UNIX (Linux, Ubuntu) and I'm trying to understand the organisation of files and directories. I stumbled upon File Hierarchy Standard (quite old it seems) and it made me wonder if this is the ACTUAL standard that is used. Also may I ask if additional links to resources to broaden my knowledge (and everyone that asks questions about FHS) on these wonderful NIX* environments.
Where can I find the Official File Hierarchy Standard for UNIX? [duplicate]
Pipelines don't work for source code because you can't process input as it comes in. You need the entire file loaded before processing begins. It gets even worse when you need multiple files for compilation (.h files for example). If you were reading from stdin you would need to stream in all of the needed files with some method of specifying file breaks between the files you piped in. The problems just grow from there. The idea behind the pipeline was that it would be a series of simple tasks. Compiling code is NOT a simple task and so it was never designed to be a part of a pipeline. Also pipeline theory said that all communication between processes in the pipeline should be in plain text to facilitate portability of individual components. By definition the output of cc or yacc or ld or anything else involved in compiling code is binary data which doesn't fit the model.
Background If think most of us agree that filters and pipes are the very foundation of Unix systems. Pipes and filters are very powerful tools. Almost all Unix utilities use the standard input and output streams by default to make it possible to use them within pipelines. It is a convention for utilities within Unix to operate standard input and standard output if no other input/output files have been specified. grep, as, sed, tr, perl, sort, uniq, bash, cmp, cat and many others are all utilities that follow this convention. But many programming utilities have abandoned this convention. Reading input The most obvious example of this is cc (the C compiler). If you invoke cc with no arguments you get this message: ryvnf:~$ cc cc: fatal error: no input files compilation terminated.This is not the only example of this: ryvnf:~$ yacc /usr/bin/bison: -y: missing operand Try '/usr/bin/bison --help' for more information.Lower-level utilities like as read standard input by default. I wonder why that is. Writing output This also applies to output. cc outputs its executable code into a.out by default. The parser generator yacc outputs its generated parser to y.tab.c. To me using standard input/output streams by default is advantageous because then you can easily connect various utilities. Like this pipe which compiles a yacc parser to executable code in one go without generating intermediate files like y.tab.c: yacc parser.y | cc -o parserMy question Why is it that utilities for programming don't use the standard streams by default as many other Unix utilities do? What is the motivation for not using standard input streams by default for these utilities? Note that I am aware that you can get cc to read standard input by using cc -x c -. This works but my question remains why it doesn't do this by default.
Why doesn't cc (the C compiler) and similar utilities use standard streams by default? [closed]
No, these utilities are not standardized. A quick look through the useradd(8) manual on RHEL6 versus OpenBSD reveals that while there are similarities, various flags differ in purpose. For a broader view, http://bhami.com/rosetta.html lists under "managing users" a variety of different commands, depending on the particular flavour of unix.
Are basic system administrator utilities such as useradd or adduser standardized? If so, where can I find the specs? (POSIX doesn't seem to encompass those, but I might need to take a better look).
Are basic system administrator utilities such as useradd or adduser standardized?
Unless you can find something that says option arguments can't start with a minus sign, then the only possible interpretation is -b=-a barSee also: POSIX Utility Conventions.
This question is somewhat similar to this: Unix/Linux command syntax Suppose I have a program foo that takes arguments -a and -b. If both a and b take a string argument what is the meaning of this foo -b -a barIf multiple b:s are allowed foo -b -a -b?? Is there a true specification of the command line syntax somewhere?
Standard command line syntax ambigiuty in interpretation rules?
The task is to preserve the log output even if an application deletes the log file. By creating a second name for the log file with ln, the data in the log will be available under two names. If one of the names is deleted, the data is still available under the other name. In a script: log=/var/tmp/install.log info=/tmp/info.log ln -f "$log" "$info"exec >"$log" 2>&1If $log does not previously exist, you will need to create it with touch "$log" before the call to ln. This assumes that both names reside on the same filesystem. This answer does not assume that you're using bash. It will work with any sh-compatible shell.
I use the following syntax in order to send standard output and standard error to $log file log=/var/tmp/install.log info=/tmp/info.log exec > $log 2>&1how to redirect both standard output and standard error also to /tmp/info.log file ?
how to send standard output and standard error to two files
There are no formal specs, but in practice a "sendmail compatible interface" means you have a MTA with a local mail injection agent named sendmail, and that if you replace the real sendmail(8) with it everything will keep running without taking notice of the change. This means implementing at the very least sendmail(8)'s options -t, -i, and -oi, and accepting messages in the same format as sendmail(8). Then again, since you're writing a replacement you're intimately familiar with all the relevant RFCs, aren't you. :)
Postfix (and lots of other stuff) claim they offer sendmail compatible interface. Since I want to write my own sendmail implementation, I was wondering what that actually means. Is there anything RFC-like describing what sendmail-compatible actually means? Like what arguments it should support and stuff?
Sendmail compatibility interface
Check the definition of the FUNC_NAME in the same spec you're quoting from:12. The token NAME shall consist of a word that is not a keyword or a name of a built-in function and is not followed immediately (without any delimiters) by the ( character. 13. The token FUNC_NAME shall consist of a word that is not a keyword or a name of a built-in function, followed immediately (without any delimiters) by the ( character. The ( character shall not be included as part of the token.So the difference is already made in the lexer, and a word like foo will turn into a NAME, not a FUNC_NAME token when not immediatedly followed by a (.
I am trying to understand how busybox's awk works so I'm looking into the standard and hit weird thing which I do not fully understand why is legal. Standard ( https://pubs.opengroup.org/onlinepubs/9699919799/utilities/awk.html , in section User-Defined Functions ) states thatWhen invoking a function, no white space can be placed between the function name and the opening parenthesis.The grammar shown later on is prefixed with:This formal syntax shall take precedence over the preceding text syntax description.non_unary_expr : '(' expr ')' | '!' expr ... | FUNC_NAME '(' expr_list_opt ')' /* no white space allowed before '(' */ | BUILTIN_FUNC_NAME '(' expr_list_opt ')' | BUILTIN_FUNC_NAMEThe grammar is completely same for both BUILTIN_FUNC_NAME and FUNC_NAME. Yet despite that, it behaves differently for user and builtin functions: +$echo | awk -P '{ print length() 1 }' 01 +$echo | awk -P '{ print length () 1 }' 01 +$echo | awk -P 'function foo() { return 0 } ; { print foo() 1 }' 01 +$echo | awk -P 'function foo() { return 0 } ; { print foo () 1 }' awk: cmd. line:1: error: function `foo' called with space between name and `(', or used as a variable or an array awk: cmd. line:1: function foo() { return 0 } ; { print foo () 1 } awk: cmd. line:1: ^ syntax error awk: cmd. line:1: function foo() { return 0 } ; { print foo () 1 } awk: cmd. line:1: ^ syntax errorWhich part of the grammar does specify this behaviour?
Why is it legal to have white space before builtin function in awk?
From your github link, follow "Audit Event Parsing Library" which has a link the the dictionary at https://github.com/linux-audit/audit-documentation/blob/master/specs/fields/field-dictionary.csv The raw CSV version is at https://raw.githubusercontent.com/linux-audit/audit-documentation/master/specs/fields/field-dictionary.csv
I am writing a converter which takes Linux Audit logs as input. I tried to find the most recent dictionary file where all the valid names of the fields are defined. I've found such a file[1] but the main website[2] says:Specs The specifications have moved to github. The following will be left in place for a while and then removed. I cannot find these information on the GitHub Wiki[3] of the Linux Audit project. Is the file[1] still the most recent and valid source of information?Links:https://people.redhat.com/sgrubb/audit/field-dictionary.txt https://people.redhat.com/sgrubb/audit https://github.com/linux-audit/audit-documentation/wiki
Where can I find the most recent dictionary of standard Linux Audit event fields?
Not reliably (or portably); on OpenBSD man -s ... lets you search by section, though outside of system or C related things, there are only sections for Fortran, Perl, and Tcl/Tk. Still, a search for say strftime in the Perl section will not find anything, as that call is hiding inside POSIX (or various other modules), and will not appear anywhere a man -k search can find it. % man -k -s 3p strftime % man -k -s 3p POSIX locale(3p) - Perl pragma to use or avoid POSIX locales for built-in operations POSIX(3p) - Perl interface to IEEE Std 1003.1 % Meanwhile, man over on Mac OS X lacks -s, and the quality and quantity of the man pages is quite poor (missing, or a random pilfering from some vintage of (Free|Open|Net)BSD). Linux likewise has a dubious record of man page maintenance ("see the info page, lol!", etc). In theory the manual pages could have been a well-maintained resource, and in theory there could be searchable sections for R or other such languages, but that's generally not what happened.
man pages are a phenomenal resource while programming in C on Linux. While looking at someone else's code, if you see something foreign you can immediate research it in another terminal with $ man 3 filenoor whatever the syntax you don't understand is. Is there a standard way to get "man" pages for other programming languages like Python, R, Javascript, or anything else? It doesn't actually have to be man, but some program I can quickly call to research something like $ man-python numpy.random.randinstead of having to Google it and use HTML documentation. The same question holds generally for other programming languages.
`man` pages for languages other than C (e.g, python, R, javascript, etc)?
It isn't a written standard, it is, however, a de facto standard, meaning it had been used and found useful, so it came to be the common way to do things. As Alex said - from common sense.
I can see that uppercase letter means default here. Is there a standard for this? I'd like to read the full standards.
What's the standard used by yum prompt "Is this ok [y/N]:"?
You're looking for Perl-style aka PCRE regular expressions but that isn't a POSIX conforming syntax and not supported by typical implementations of the standard command-line tools like sed. What is supported are the syntax known as Basic Regular Expression (BRE) and Extended Regular Expression (ERE). In sed the former is the default and the latter is enabled with -E (in GNU sed -r also works). You'll occasionally see versions of standard tools with some support for PCRE (e.g. GNU's grep has the -P flag) but this is the exception not the norm. See the Standards section of Wikipedia's regex page for details.
I have asked a question insert a string to a list variables in text file [use sed] In which @RomanPerekhrest showed me a different regex syntax. \(=([^)]*\)) can capture [^)]* as group 1 . This is confusting for me . You can check the result on https://regex101.com/r/DRChkE/2https://regex101.com/r/LItVNg/1This \(([^\)]*)\) is the correct one in my mind, but it is broken in sed. So I wonder how to make sed use the regex syntax standard as python or javascript (common standard in many languages).
How to make sed regex syntax work as python or javascript? [duplicate]
You would advocate for this on the mailing lists dedicated to the specific tools you are interested in. The available GNU mailing lists are available here: https://lists.gnu.org/mailman/listinfo/ If one or other of the tools you are interested in is not represented by any GNU mailing list, then you would have to investigate who's maintaining it and whether there's an associated mailing list that they maintain. Note that feature requests to open source projects have a much higher chance of getting accepted if you can provide a patch of the source code that implements the feature and that works.
Call me a dreamer, but imagine a world where "every" CLI tool we use had an option toproduce astable output, say in JSON. Programmatic use of CLI tools like ls, free, df, fdisk would be abreeze. The way GNU standardized argument syntax conventions, can it standardize the output along the lines of "--json produces atool-specific report formatted according to JSON spec"? Has this been attempted and rejected perhaps? If not, how do we push for something like this?
How to advocate for GNU to add a "--json" parameter for all CLI commands to be compliant? [closed]
Please, no. WRT regular text: single quotes, fine. Double quotes, okay. Backticks are only used literally (eg, as they are with the shell) and not as quotes. There are also the extended charset characters “ (left double quote) and ” (right double quote), but since they are not on a normal keyboard, the " is usually used in place of both of them. There's also a right single quote and left single quote, but since they're not on the keyboard either the apostrophe ' usually stands in for them. In the context of programming (including shell scripting), what quotes mean varies from language to language, none of which are specific to linux. Programming languages AFAIK restrict themselves to the ASCII character set, so the plain " and apostrophe ' for the single quote. I have seen documentation here and there that does the kind of thing you are talking about. IMO it's ugly and ridiculous, but to each their own. It certainly does does not indicate anything beyond clumsiness, and even more certainly does not mean anything in a programming or shell context (other than "syntax error").
For example, 'foo bar' would be quoted as `foo bar', or ``foo bar''. Is it encouraged or general practice to use this quoting syntax? It seems to be quite common in some documentation.
Is it normal to use the grave (`) symbol, followed by an apostraphe (') to quote? [duplicate]