date int64 1,220B 1,719B | question_description stringlengths 28 29.9k | accepted_answer stringlengths 12 26.4k | question_title stringlengths 14 159 |
|---|---|---|---|
1,486,900,441,000 |
Without Oh-My-Zsh, I can pushd two identical path:
$ dirs
~
$ pushd Desktop
Desktop ~
$ pushd ~
~ Desktop ~
With Oh-My-Zsh:
$ dirs
~
$ pushd Desktop
Desktop ~
$ pushd ~
~ Desktop
How do I disable this? I want the original Zsh behavior.
|
(Insprired by this answer) It is set in $ZSH/lib/directories.zsh:
setopt auto_pushd
setopt pushd_ignore_dups
auto_pushd makes cd behave the same as pushd. However, this would result in an directory stack overflow if you keep changing directory, so they set pushd_ignore_dups as well, to limit the stack. This is not a problem for me, since I disabled auto_pushd.
Therefore, add unsetopt pushd_ignore_dups in ~/.zshrc.
Reference
Options - Zsh documentation
| Oh-My-Zsh remove duplicated path in directory stack |
1,486,900,441,000 |
For context, I'm using zsh. Every time I use locate, I want to pass the -i and -A flags.
Usually, if I can get away with it, I create an alias with the same name as the existing command to do this. But according to this question, aliases can't accept arguments, so I have to use a function instead. Usually I stop there because the idea of a function with the same name as a command feels wrong to me, though I can't say why.
I was about to finally create such a function when I had this thought: this is a common pattern for me, wanting to default flags for command; is there an easier way of going about it? Perhaps zsh provides a better solution to this problem?
That brought me to another thought: is it an anti-pattern to override an existing command? I've always done it because it allows me to skip an association in my head: e.g., "Why doesn't ll have a man page? Oh yeah: ll really means ls -la. I need to do man ls, not man ll. Etc."
To summarize:
Is it alright/idiomatic to override an existing command with an alias/function?
Does zsh or some other tool provide a more direct way to default flags for a specific command?
|
I am really surprised by that other post you mentioned, as it can be very misleading. Just because an alias doesn't use parameters doesn't mean that aliases cannot set parameters. Of course you can put options in an alias, but it is just restricted, meaning, the alias is replaced in one place.
$ alias ls='ls -l'
$ ls
# will run: ls -l
$ ls foo
# will run: ls -l foo
The problem that other question poses is if you want to add options to a alias that has a argument.
so if you had an alias:
$ alias movetotrash='mv ~/Trash'
# no way to use inject anything inside 'mv' and '~/Trash'
So in your case
$ alias locate='locate -i -A'
# will expand to 'locate -i -A' and then whatever else you type.
As for your specific questions:
It is quite common for linux distributions to ship with default "options" via aliases, for example, ls frequently has a alias ls 'ls --color=auto' or for root login you might see alias mv 'mv -i'. So it can be considered a standard way of providing better defaults to users and uses the same name of the underlying binary. If a user doesn't want to use an alias and it is set in the standard environment, they can use unalias to unset the alias permanently, or when running a command using a backslash, such as \mv a b will prevent alias expansion for that execution (as does using the full path, like /usr/bin/mv a b)
I don't believe that zsh provides any extra capabilities in this area, and certainly nothing that would be a "standard". People often write wrapper shell scripts and sometimes shell functions. But for trivial software, alias is often the solution people use. If the program is complicated enough, it will usually gain an rc file for common user preferences.
I think one tool that tried to make options a bit easier was the popt library, which allowed users to create their own options to software, but the popt library isn't widely used, and I don't think it had the ability to set the default.
| How can I/Should I default flags when running a command? |
1,486,900,441,000 |
I have looked for a solution to this OhMyZSH! problem for a few days now, but can't find a solution.
Admittedly, I do not understand how zle really works, same for bindkey. Same goes for the way terminal emulators send "control sequences", and what the "terminal type" means (xterm, versus xterm-256-color, and others). Same for the "Application mode"
The setup
I have 2 machines where the latest version of OhMyZSH is installed, commit c3b072:
machine A: SLES 11 SP4, running zsh 4.3.6 (x86_64-suse-linux-gnu)
machine B: Ubuntu 16.04, running zsh 5.1.1 (x86_64-ubuntu-linux-gnu)
I connect to either machine using Putty running on Windows, with terminal type xterm, and in UTF-8 translation mode.
My zshrc files are pretty much vanilla OhMyZSH templates, I have just changed the prompt to dieter on machine A, and powerlevel-9k [https://github.com/bhilburn/powerlevel9k] on machine B.
What I observe on machine A (aka the "bad" one)
When I edit my command line, the Left and Right cursor keys move one whole word (instead of 1 single character).
Home and End keys though, bring the cursor to the beginning and end of the line, as expected.
This described behaviour applies when in emacs mode (bindkey -e).
When I go to vim mode (bindkey -v), the Left and Right arrows move 1 character, but the Home and End keys don't move the cursor to the beginning and end of the line. Instead, they switch the case of the character under the cursor.
What I observe on machine B (aka the "good" one)
Left and Right keys move the cursor one single char. Home and end keys move the cursor to the beginning and end of line resp. Ctrl+A and Ctrl+E combos bring my cursor to the beginning and end resp.
This is the behaviour I would like for all my shells.
What I have found so far
I think it is a bindkey issue. But I know next to nothing about that, and I've had a hard time finding any doc on this zsh built-in.
Running zsh -v on both machines at login time gives very different results, despite similar .zshrc files.
Could someone explain to me what is causing these 2 machines to behave so differently, and how I can change my configuration so that consistency is regained, and all my shells behave like on machine B (aka the "good" one)?
I'm sure you will let me know if you need more information that I don't know is needed.
Many thanks
|
You must configure your terminal type as putty, putty-256color, or putty-sco when using PuTTY. They are the only terminal types whose entries in the terminfo database correctly describe PuTTY.
It is a widespread incorrect assumption that terminal emulators are all compatible with XTerm, and that the xterm and xterm-256color entries in the terminfo database correctly describe them.
This erroneous thinking is called out in Thomas Dickey's XTerm FAQ and it is worth observing that the xterm and xterm-256color entries do not even describe all versions of XTerm, let alone other terminal emulators.
PuTTY's doco such as the page hyperlinked there by M. Dickey, even today 16 years since the putty entry was added to terminfo, unfortunately promotes this mis-use of the xterm terminal type, but a mis-use it is, and this is the very sort of application misbehaviour that occurs.
Comparing the terminfo database entries for xterm-256color and putty-256color reveals what is happening with your ⇱ Home and ⇲ End keys:% infocmp xterm-256color putty-256color|grep -F kend
kend: '\EOF', '\E[4~'.
% infocmp xterm-256color putty-256color|grep -F khome
khome: '\EOH', '\E[1~'.
%
As you can see, an application that is told that it is dealing with XTerm expects to receive (from the terminal) the control sequence ␛OH for the ⇱ Home key and the control sequence ␛OF for the ⇲ End key. But PuTTY actually sends the control sequences ␛[1~ and ␛[4~ (respectively) instead.
Your application, the Z shell, expecting the the XTerm keyboard control sequences (because you have erroneously told it that your terminal has the type xterm), does not recognize the PuTTY control sequences, and in fact breaks them down into the vi-mode commands to exit insert mode (␛) and swap the case of the current character (~).
Further reading
Where does the TERM environment variable default get set?
Fish shell shows dark-grey "âŽ" characters in prompt
https://unix.stackexchange.com/a/444270/5132
| Using putty, Left and Right keys move cursor one word, instead of one char |
1,486,900,441,000 |
function projectopen {
local di_files=(*.xcworkspace */*.xcworkspace *.xcodeproj */*.xcodeproj)
# open first exsit file
ls -d -f -1 $di_files 2>/dev/null \
| head -1 \
| xargs open
}
I write a shell function to quick open xcworkspace in terminal. But when I declare di_files as a local var, then the function is broken, and log
projectopen:1: number expected
I use zsh on Mac OS. Why this happen and how to fix it?
|
In older versions of zsh you cannot initialise an array with local (or typeset/declare) like that, you need to separate it, e.g.
local -a di_files # explicit array
di_files=( ... )
The feature to permit declaration and array assignment together was added in v5.1.
I believe the error you see is because zsh is treating the initialisation as scalar and () as a glob qualifier.
You can also probably replace your elaborate pipeline with the simpler
open "${di_files[1]}"
Finally, including handling for no matching files:
function projectopen {
setopt local_options nullglob
local di_files=(*.xcworkspace */*.xcworkspace *.xcodeproj */*.xcodeproj)
# open first existing file
[ -n "${di_files[1]}" ] && open "${di_files[1]}"
}
With the nullglob option each glob expansion which matches no files is replaced with an empty string (I suspect you may have nonomatch set, a related option).
| Declare as local var will break a function and log out "1: number expected" |
1,486,900,441,000 |
I am using zsh in Babun (Cygwin with oh-my-zsh and some extras).
I noticed some odd behavior, it looks like cd is behaving like pushd?
{ ~ } » mkdir foo
{ ~ } » pushd foo
~/foo ~
{ foo } » popd
~
The above is fine and expected, but see the below.
{ ~ } » cd foo
{ foo } » dirs
~/foo ~
I tried checking if there was some alias being set somewhere, but I saw no such thing.
{ foo } » alias | egrep "(cd|pushd)"
-='cd -'
1='cd -'
2='cd -2'
3='cd -3'
4='cd -4'
5='cd -5'
6='cd -6'
7='cd -7'
8='cd -8'
9='cd -9'
grt='cd $(git rev-parse --show-toplevel || echo ".")'
pu=pushd
Why is my cd appending dirs? It's not really a problem, I am more just curious.
|
I see now. oh-my-zsh does setopt auto_pushd which is described here as:
AUTO_PUSHD (-N)
Make cd push the old directory onto the directory stack.
| Why is cd appending dirs like pushd? |
1,486,900,441,000 |
I have an ever-expanding .zshrc file that was getting out of hand so I decided to try to fix it by breaking it into modular files and sourcing each of them. This works for the most part, but I seem to have some scoping issues related to variables.
Each module file contains a function matching corresponding with the name of the file. For instance: nvm..zshrc contains the function (called by the main .zshrc file) named zshrc_config_load_nvm {}.
Below is a simplified form of the setup I'm using.
The main .zshrc file
Note that I've thoroughly tested this file and everything in it works just fine.
# Load all config files
# This method basically copied directly from the .oh-my-zsh.sh file.
for config_file ($ZSH_CUSTOM/*.zshrc(N)); do
# Skip self-inclusion
if [[ $config_file==".zshrc" || $config_file==".zshenv" ]]; then
continue
fi
# The (D) modifier will escape the path so it can be passed to `basename`
# without quotes. the second param in `basename` removes the file extension.
local handle=$(basename ${(D)config_file} .zshrc)
# If the file contains the expected callback function name ...
# The :t filter will remove the path and file extension.
if [[ $(command -v "zshrc_config_load_${handle}") ]]; then
# ... Add it to the list of functions to call.
ZSH_CONFIG_HANDLES+=($handle)
fi
# Each config file will call the register function above.
source $config_file
done
for handle ($ZSH_CONFIG_HANDLES); do
func="zshrc_config_load_${handle}"
# Call the function
$func
done
unset config_file handle func
nvm.zshrc
# This line is copied directly from the documentation.
export NVM_DIR="$([ -z "${XDG_CONFIG_HOME-}" ] && printf %s "${HOME}/.nvm" || printf %s "${XDG_CONFIG_HOME}/nvm")"
# The callback function
function zshrc_config_load_nvm {
# Unable to access the $NVM_DIR variable in this scope.
source $NVM_DIR/nvm.sh --fast-reuse
# Error: /nvm.sh does not exist.
}
The Question
How do I make exported global variables accessible from within the scope of another function, but without passing those values in as arguments?
According to this answer by Gilles 'SO- stop being evil'...
export [in] zsh is shorthand for typeset -gx, where the attribute g means “global” (as opposed to local to a function) and the attribute x means “exported” (i.e. in the environment).
... Therefore I assume that the $NVM_DIR variable should be available from within another function.
|
Your functions will see the variable that you have set earlier (and exported or not) provided they haven't been set in a subshell or not declared local to some function that has since returned.
Your problem comes from unrelated mistakes in your code:
for config_file ($ZSH_CUSTOM/*.zshrc(N)); do
# Skip self-inclusion
if [[ $config_file==".zshrc" || $config_file==".zshenv" ]]; then
continue
fi
[[ somestring ]] returns true if somestring is not the empty string. $config_file==".zshrc" is obviously not the empty string, so that test will return true regardless of the value of $config_file. So your loop won't do anything.
You probably meant something like [[ $config_file = .zsh(rc|env) ]], though that's a bit pointless given that $config_file will never be either .zshrc nor .zshenv as those are hidden files, so not included by default in glob expansions and anyway $config_file also starts with /path/to/zsh_custome/ (and .zshenv doesn't end in .zshrc).
if [[ $config_file -ef $0 ]] continue to check that $config_file is not the script currently being sourced may make more sense.
Other notes:
export NVM_DIR="$([ -z "${XDG_CONFIG_HOME-}" ] && printf %s "${HOME}/.nvm" || printf %s "${XDG_CONFIG_HOME}/nvm")"
Would better be written as:
if (( $+XDG_CONFIG_HOME )); then
export NVM_DIR=$XDG_CONFIG_HOME/nvm
else
export NVM_DIR=~/.nvm
fi
In:
local handle=$(basename ${(D)config_file} .zshrc)
The D parameter expansion flag (which turns /home/you/file to ~/file for instance) doesn't make sense.
Sounds like you want local handle=$config_file:t:r (root of tail of the file).
if [[ $(command -v "zshrc_config_load_${handle}") ]];
Is better written as:
if command -v "zshrc_config_load_${handle}" >& /dev/null;
Which avoids the fork. Or possibly if (( $+functions[zshrc_config_load_${handle}] ));.
Instead of doing var=... ... unset var, you can use local in a function or anonymous function:
function {
local var
...
}
If there was a $var from an outer scope (or coming from the environment), that would then leave it alone instead of ending up unsetting it.
| Variable Scope in ZSH: How to access global variables from within function? |
1,486,900,441,000 |
I've installed Arch about a week ago, and since then I been struggling with the powerline fonts. But after installing the pkg powerline-fonts, I configured the .zshrc file by adding these lines:
powerline-daemon -q
. /usr/share/powerline/bindings/zsh/powerline.zsh
The best I could do is commenting the line in the .zshrcfile that chooses a specific theme and letting the above code to run, and looks like this: powerline-fonts fix.
Still, the oh-my-zsh themes don't work; for example this is the agnoster theme: agnoster theme.
Another issue I have is that the symbols or the numbers are not shown properly in the terminal, any terminal, for example when using broot:br listing
or bat: bat
I think these problems are linked and that's why I've asked the two questions in one.
My question is: How could I fix this and have the oh-my-zsh themes work properly?
On my vm they look like this:agnoster-theme and bat.
I would like to make them look identical.
|
Good Ol' Locale
One issue I have had come up is not having my locale set, which causes all sorts of headache and misery to befall the unaware. To set it, go to /etc/locale.gen and uncomment the US English locale: en_US.UTF-8 UTF-8 then as root run locale-gen and as root again localectl set-locale LANG=en_US.UTF-8 just to be extra sure. Then reboot and if the issue persists check out this guide from Arch Wiki and see if the steps there work for you.
Alternative Installation Method
Additionally and to rule out another possible problem, you can try an alternative method of installing powerline, first you will need to download python-pip, then you will use it to download powerline.
sudo pacman -S git python
su -c 'pip install git+git://github.com/Lokaltog/powerline'
Now this new installation of powerline is in /usr/lib/python3.9/site-packages/powerline/ so add the following to .zshrc
if [[ -r /usr/lib/python3.9/site-packages/powerline/bindings/zsh/powerline.zsh ]]; then
source /usr/lib/python3.9/site-packages/powerline/bindings/zsh/powerline.zsh
fi
and you may want to alternatively install the powerline fonts, to do so try the below:
wget https://github.com/Lokaltog/powerline/raw/develop/font/PowerlineSymbols.otf https://github.com/Lokaltog/powerline/raw/develop/font/10-powerline-symbols.conf
sudo mv PowerlineSymbols.otf /usr/share/fonts/
sudo fc-cache -vf
sudo mv 10-powerline-symbols.conf /etc/fonts/conf.d/
This is not an exhaustive list, there is simply a lot of different avenues to pursue with rectifying this one which I haven't had come up in a long time (I scripted out my installation from ISO then another one provisions my dotfiles and installs my programs to taste, which spares me these headaches generally but causes a bunch of its own) but I do hope it helps or leads you along the right path!
| How to fix powerline fonts and symbols error in shell? |
1,486,900,441,000 |
(I originally posted this on apple.stackexchange but then I found this one which is probably a better place)
I have a big problem. I've freshly installed mac os and was setting up my terminal. I installed iTerm, zsh and oh-my-zsh (following this tutorial, basically: https://medium.com/ayuth/iterm2-zsh-oh-my-zsh-the-most-power-full-of-terminal-on-macos-bdb2823fb04c)
After installing oh-my-zsh, I got this error message (this is just a random question showing that same error message):
https://stackoverflow.com/questions/61554566/how-to-avoid-bunch-of-oh-my-zsh-messages-showing-whenever-i-open-iterm-termi
I remember that the fix to this was running the suggested command (I've done this a few years ago):
compaudit | xargs chmod g-w,o-w
I think that was the last thing I did. Now every time I start a terminal (either Mac OS' Terminal or iTerm, doesn't matter) it gets stuck at "login" with a blank screen. I don't get any input prompt.
Even worse, I can't even shut down the mac anymore. When I click on shut down or restart, every app is closed and I see my wallpaper and nothing happens. I have to kill it via the power button.
After restarting, the terminal works perfectly again until I close it with CMD-q. Once I reopen it, it's stuck again at "login".
I've looked everywhere and can't find a solution.
I've seen this question (https://apple.stackexchange.com/questions/267668/terminal-login-hangs) but it didn't help. I tried almost everything proposed there.
I would greatly appreciate any help or thoughts on this.
Also, it works when I boot into safe mode. There, everything is fine.
|
The problem is caused by iTerm having problems with the first beta version of Mac OS Big Sur. A specific setting causes the problems I've experienced. See https://gitlab.com/gnachman/iterm2/-/issues/8965 for details.
Until fixed, the workaround is this (taken from the GitLab issue):
Workaround:
Disabling Enable session restoration under Preferences > Advanced > Session resolves prevents the hang ups, albeit with the obvious loss of functionality.
Note: A computer restart may be required before this change takes effect.
| terminal stuck at “login” - blank screen (after installing oh-my-zsh, I think) |
1,486,900,441,000 |
Oh-my-zsh has a plugin option (plugins = (gcloud, ...)) which allows installing gcloud completions.
When I add "gcloud" to plugins, I expect that the completion will be sourced during shell initialization, but it doesn't work on NixOS (version 19.03).
How to install gcloud completions on NixOS with oh-my-zsh?
|
Instead of adding gcloud to programs.zsh.ohMyZsh.plugins, I found that I had to manually source the completion script. To do this:
Add pkgs.google-cloud-sdk to environment.systemPackages of your configuration.nix file, and then update the zshrc section:
programs.zsh.promptInit = ''
export CLOUD_SDK_HOME="${pkgs.google-cloud-sdk}"
source "$CLOUD_SDK_HOME/google-cloud-sdk/completion.zsh.inc"
'';
| How to install Google Cloud completion in NixOS with Oh-My-Zsh? |
1,486,900,441,000 |
I got an image from Facebook which is beautiful i want to make my Arch Linux machine just like this image,
I have installed Arch Linux with Deepin Desktop Environment also installed neofetch, i am stuck on zsh shell theme which you can see in image, i tried to search in oh-my-zsh repositorieshttps://github.com/robbyrussell/oh-my-zsh/wiki/Themes but can't find also i am unable to install Arc-Flatabulous theme & Flat-Remix icons
|
Try this below instruction:
first list all the install shell in your current system:
chsh -l
then change your shell like this: (in your case zsh:
chsh -s /bin/zsh
and now restart or logout and login.
then install oh-my-zsh theme from here :
https://github.com/robbyrussell/oh-my-zsh
installation command looks like:
sh -c "$(wget https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh -O -)"
after this open file ~/zshrc: nano ~/.zshrc
and change the ZSH_THEME to: ZSH_THEME="fino" (you can set to any theme you like)
now open a new terminal.. and check its work or not.
let me know this works or not. if its work..
add a screenshot in your question and mark my post as answer.
| Which zsh shell theme is this? |
1,486,900,441,000 |
I have recently re-installed ubuntu 14.04 lts and I installed my favorite shell (zsh) but I am having an issue now.
When I type, sudo su it comes back with an error stating /root/zsh can not be found.
I am not sure what I need to do to fix this as this is the first time I have had this error when using this system.
Also when I do, sudo chsh -s /bin/zsh
I get
PAM_AUTHENTICATION failed
Any help would be appreciated.
|
su executes your login shell as indicated in the login database. This is /root/zsh, which doesn't exist, so the command su fails.
chsh only accepts changing the shell of a user who currently has a valid shell (listed in /etc/shells). Since /root/zsh is not accepted, chsh fails. The root user can change anyone's shell, but this test is made after the validity check for the current shell.
However sudo itself doesn't care about your login shell (unless you run sudo -s or sudo -i). So you have plenty of ways to repair your system: sudo /bin/zsh gives you a shell, from which you can run vipw and correct the entry for root. You can even run sudo vipw directly.
I recommend starting a root shell in one terminal and doing the configuration change in another terminal. Don't exit that root shell until you've confirmed that the system is back to a working state by testing that sudo -i or sudo su works.
| Sudo su issue on ubuntu 14.04 lts: /root/zsh can't not be found |
1,486,900,441,000 |
I am new to zsh and I like it a lot, especially with oh-my-zsh plugin. I installed oh-my-zsh with its default values and can't figure out how to turn off autocompletion for specific commands, that I often use, such as:
sudo mc or sudo gem update. The thing is that I have .mc directory and .gem directory and zsh proposes corresponding autocompletions (for .mc and .gem).
Generally I would like to config zsh so that sudo is not considered a separate command (which it is not) with the following as a params. Is there a config for that?
|
Ignoring directory patterns is fairly painless. You can add the following to your ~/.zshrc.
The first line ignores .mc and .gem patterns after issuing cd [TAB]. The next line ignores them after issuing sudo [TAB].
zstyle ':completion:*:cd:*' ignored-patterns '(*/)#.mc' '(*/)#.gem'
zstyle ':completion:*:sudo:*' ignored-patterns '(*/)#.mc' '(*/)#.gem'
| How to disable autocompletion for sudo ...? |
1,486,900,441,000 |
Why will this
bindkey '^ ' end-of-line
works, and accept the suggestion, but
function accept {
zle end-of-line
}
zle -N accept
bindkey '^ ' accept
this won't work.
I don't understand why. I also tried to replace end-of-line with autosuggest-accept in the function, but still nothing happens...
What I try to do is having two keybinding:
ctrl+space: accept the suggestion and execute the line
easily done by bindkey '^ ' autosuggest-accept
ctrl+alt+space: accept the suggestion, add sudo at the beginning and execute.
I tried this:
function insert-sudo-accept {
zle end-of-line
LBUFFER="sudo $LBUFFER"
zle accept-line
}
But again as I said zle end-of-line does not work, please help.
|
When a keybinding’s widget is activated, the Zsh Line Editor (ZLE) sets the $WIDGET parameter to the name of the activated widget.
In turn, zsh-autosuggestions checks whether the value of $WIDGET is a member of $ZSH_AUTOSUGGEST_ACCEPT_WIDGETS. If so, it will accept the suggestion.
However, inside your widget function, when you call zle end-of-line, this will not change the value of $WIDGET.
There are three ways to solve this:
Bind zsh-autosuggestion’s own autosuggest-accept widget to CtrlSpace:
bindkey '^@' autosuggest-accept
Call zle end-of-line -w. This will update $WIDGET to the name of the widget you’re calling.
Add your widget to $ZSH_AUTOSUGGEST_ACCEPT_WIDGETS:
ZSH_AUTOSUGGEST_ACCEPT_WIDGETS+=(
<insert widget name here>
)
| end-of-line widget not working in functions (zsh-autosuggestions) |
1,486,900,441,000 |
I'm modifying the intika2 theme in oh-my-zsh to add the current pyenv setting to my prompt. OMZ includes a pyenv_prompt_info command & I added it to the LEFTINFOS variable in the intika2 theme to do this. This provides the correct pyenv version whenever the .zshrc file is sourced, but not on subsequent prompts after changing the pyenv version.
Minimal version of the proposed theme modification:
function prompt_char {
if [ $UID -eq 0 ]; then echo "#"; else echo $; fi
}
LEFTINFOS="$FG[gray][pyenv=$(pyenv_prompt_info)] [%~] %{$reset_color%}"
PROMPT='
╭─$LEFTINFOS
╰─$(prompt_char)%{$reset_color%} '
Note that LEFTINFOS was defined in the intika2 theme, not something I added.
This gets me:
If I change PROMPT to
PROMPT='
╭─$FG[gray][pyenv=$(pyenv_prompt_info)] [%~] %{$reset_color%}
╰─$(prompt_char)%{$reset_color%} '
then I get the behavior I expect.
I've confirmed that prompt_subst is set. I've tried various tweaks to LEFTINFOS definition, such as %{$(pyenve_prompt_info%), without success. I've looked at this
The fix, i.e. replacing LEFTINFOS, is easy enough; I want to understand why the command substitution is not working.
|
You have the wrong quotes. The definition of LEFTINFOS uses double quotes, so what's inside the quotes is evaluated when the definition is evaluated, instead of when the prompt is calculated. You need to arrange for the value of PROMPT to contain the string $(pyenv_prompt_info). So define LEFTINFOS to contain $(pyenv_prompt_info), using single quotes so that $… inside isn't expanded. Conversely, the value of PROMPT needs to contain the value of LEFTINFOS, not the string $LEFTINFOS (otherwise your prompt would contain $(pyenv_prompt_info) instead of the result of expanding it). So use double quotes when defining it.
For the other variables, it probably doesn't matter much, but if you want to be able to tweak colors during a session, they also need to be expanded during prompt calculation and not before.
LEFTINFOS='$FG[gray][pyenv=$(pyenv_prompt_info)] [%~] %{$reset_color%}'
PROMPT="
╭─$LEFTINFOS
╰─$(prompt_char)%{$reset_color%} "
Also, as presented here, $(prompt_char) is a fancy and slow way of writing %(!:#:\$), except that %(!…) uses the effective UID, which makes a difference only if you temporary drop privileges from a root shell.
Using psvar and %1v, %2v, … can make prompt definitions easier to read and write, but I don't know if oh-my-zsh interferes with that.
| oh-my-zsh prompt substitution |
1,486,900,441,000 |
When I open a new terminal it takes a couple seconds for the shell to load, when I open a new pane or window in tmux it might even take a second longer. The delay is about 3 seconds.
I'm using zsh with oh-my-zsh and the ohmyzsh plugins: git, vi-mode, history-substring-search.
My path looks like:
/home/alec/.nvm/versions/node/v14.6.0/bin:/home/alec/.composer/vendor/bin:/home/alec/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/home/alec/code/bin
Previously I had wondered if having a git repo on the path would be problematic. The final location in that path ~/code/bin used to be ~/bin and there was the .git database inside it. Now the .git directory is in ~/code (which seems to me like it would prevent the shell from looking through it for executables) but this hasn't delivered any performance improvements.
I don't know any other guess-and-check possibilities, or any logical troubleshooting procedures to perform/investigate.
Any suggestions?
|
Add: set -x to the top and set +x to the bottom of ~.zshrc to get a lot of output about what's being run during shell startup. (It's helpful to keep that file open in a separate window/terminal/editor during the whole debug process)
It can be hard to know what's proper and what's problematic among all that output... but if you notice something that you recognize, that's a good place to start. In my case there were many lines about nvm, the "node version manager". Disabling the nvm lines in my .zshrc file eliminates two seconds from the shell startup!
To use nvm without the performance burden, https://www.ioannispoulakas.com/2020/02/22/how-to-speed-up-shell-load-while-using-nvm/ suggests a couple possible solutions.
| why is shell (new terminal, new tmux panes/windows) slow to load? |
1,486,900,441,000 |
So I installed zsh a few days ago, and I'm loving it. But when I type something in, it shows me the possible completion using the autosuggestions plugin, but I cannot fill it using tab, i have to use the arrow keys. Pressing tab opens a menu of possible completions and/or a list of subdirectories and files. I want to have no menu completions and the only completions to be done through the autosuggestions plugin.
I've been tinkering for a few hours trying to get this so if anyone knows how to achieve this I would appreciate some help
(debian using ohmyzsh)
|
You can unload the completion system completely like this:
zmodload -u zsh/compctl zsh/complete
bindkey '^I' forward-word
Instead of inserting completions, Tab will now accept the next word from zsh-autosuggestions.
Before you give up completely on completions, though, may I suggest you give my zsh-autocomplete plugin a try? It gives you Visual Studio Code -style, type-head autocompletion in Zsh. And yes, you can use both zsh-autosuggestions and zsh-autocompletion in parallel.
| How to disable all menu tab completions in ZSH. I have the zsh-autosuggestions plugin installed, and i want that to be the only form of completions |
1,486,900,441,000 |
I constantly need to close and re-open programs. To do this I press Control+C > Up Arrow > Enter. However, I have more than one program and need to run different commands for these programs. If I run another command in a new terminal the history changes for the original terminal and the up arrow is no longer the last command. I'm forever accidentally running random commands in the terminal.
I have tried Control+R to search history and !! but I do this too frequently and they are too slow.
The ideal situation would be that history for a terminal did not change once the terminal was opened. Even better if that can be done only for arrow keys.
The closest I have gotten is a delay on updating the history.
Any suggestions would be greatly appreciated.
|
There was a comment that was deleted that explained that Bash did not exhibit the same behavior. That great comment helped me find How to make oh-my-zsh history behavior similar to Bash's?.
I updated ~/.profile with:
bindkey "$terminfo[kcuu1]" up-line-or-history
bindkey "$terminfo[kcud1]" down-line-or-history
Which has solved the problem.
| Run the same command |
1,486,900,441,000 |
I am trying to execute the gpustat command after SSHing into a remote server.
I am using z-shell + oh-my-zsh.
I put the gpustat command into my .zshrc file.
However, after logging in, I get the error message:
command not found: gpustat
What I find confusing is that when I source the .zshrc file, the gpustat command is executed and works.
|
It looks like you're trying to run gpustat in your .zshrc file before it has been added to your $path. My guess is that its added to your path somewhere later in your .zshrc, which would explain why it works when you source your .zshrc file manually: At that point, your whole .zshrc file has already been sourced once and gpustat has been added to your $path at that point.
| zsh - run gpustat command after login |
1,486,900,441,000 |
First, let's assume that I have:
alias foo='path/to/my/program'
in my .zshrc, then I created a completion script ~/.oh-my-zsh/completions/_foo for it, where inside the file I have:
#compdef foo
_foo() {
echo "hello"
}
_foo
So, I expected that when I type foo [tab] from shell I will see
$foo [tab]
hello
but instead I got
$ foo [tab]_foo
The text _foo was just printed out after I pressed tab.
Do you have any idea for solving this problem?
|
This is an answer about zsh in general. I don't know oh-my-zsh.
By default, zsh expands aliases before attempting completion. This is usually the right thing. As a consequence, associating a completion function to the name of an alias only has an effect when you bypass the alias, for example after \foo Tab.
You can turn off this behavior with setopt complete_aliases. But you'll lose completion for all aliases for which you don't set up completion explicitly.
If you want to have a special case for foo, the best way is to make it a function instead.
function foo {
path/to/my/program "$@"
}
This doesn't explain why _foo is printed. Maybe some oh-my-zsh weirdness.
| Zsh completion script found but not executed |
1,486,900,441,000 |
Is there a way to remove the trailing forward slashes in the tab-completion output of Zsh when I start writing a cd command and tab to see a list of directories?
E.g.
~ cd <tab>
Adlm/ Desktop/
Applications/ Development/
I was wondering if there's any way to remove the slashes after the directory names, to show Adlm instead of Adlm/, etc.
|
In zsh, it's:
set +o list_types
When using complist, you can also change its color to make it less visible:
zstyle ':completion:*' list-colors tc=33 ${(s.:.)LS_COLORS}
to make it yellow (less visible on a terminal with white background), and use the GNU ls colors (assuming you've run eval "$(dircolors)") for the rest.
| Remove forward slash when tabbing to see a list of directories |
1,486,900,441,000 |
I'm using zsh on MacOS El Capitan. I'm wondering how auto completion has to be parameterized to resolve aliases as well.
When I used bash, my .bash_profile contained the following:
alias mdb "mongo -uadmin -pXXX --authenticationDatabase admin --host "
complete -W "$HOSTNAMES" mdb
HOSTNAMES is a list of over 4000 FQDN's.
Doing so I could type mdb someHosttabtab to see a list with all hosts beginning with someHost. Once the right host selected, the command got completed to mongo -uadmin -pXXX --authenticationDatabase admin --host someHostFoo.
Right now, I want to use oh-my-zsh so I copied the above mentioned lines in my .zshrc file. However, when the hostname list exceeds round about 1500 entries, auto completion becomes very slow. For that reason I replaced complete -W "$HOSTNAMES" mdb with compctl -c "$HOSTNAMES" mdb in my .zshrc file. However, this wont work, even if I set setopt complete_aliases in my .zshrc.
Today I read that one should better write completion functions for commands since compctl is deprecated. I came up with this but this will only suggest host names after having typed mdb hoststabtab when $HOSTNAMES contains very few host names:
#compdef mongo mdb
#autoload
_mongo_hosts(){
mhosts=$HOSTNAMES
}
local -a _1st_arguments
_1st_arguments=(
"--host:host to be connected to"
)
local expl
local -a mhosts
if (( CURRENT == 2 )); then
_describe -t commands "mongo subcommand" _1st_arguments
return
fi
case "$words[2]" in
hosts)
_mongo_hosts
_wanted mhosts expl 'known hosts' compadd -a mhosts ;;
esac
Furthermore, by this approach, mdb is not yet replaced by mongo -uadmin -pXXX --authenticationDatabase admin --host.
Follow up
I discarded the above shown compdef approach. My current workaround is to add the following two lines to my .zshrc:
zstyle ':completion:*' completer _expand_alias _complete _ignored
zstyle ':completion:*:(ssh|scp|sftp|host):*' hosts $HOSTNAMES
The first line is to expand aliases as well, here my alias mdb.
The second line allows to cycle through all host names when commands like ssh, scp, sftp or host are used. The same could be achieved by this line:
_hosts() {compadd $(echo $HOSTNAMES | tr "\n" " ")}
So with this approach, I have to type first ssh someHosttabtab, choose the host and then replace ssh by mdb so it will complete to mongo -uadmin -pXXX --authenticationDatabase admin --host someHostFoo
This works but isn't perfect. I'd prefer to have the same auto completion experience I had using bash, implemented by the first shown two lines here in my question. How to achieve this with zsh and and more than 4000 host names?
Thank you!
|
I found a solution which works exactly as I wanted. Only the following three lines are required in .zshrc:
mdb() {mongo -uadmin -pXXX --authenticationDatabase admin --host "$@"}
compctl -k "($(echo $HOSTNAMES))" mdb
zstyle ':completion:*:(ssh|scp|sftp|host):*' hosts $(echo $HOSTNAMES)
The function mdb() replaces my former alias mdb.
The compctl command completes functions like mdb with the array of $HOSTNAMES.
The zstyle instruction completes commands like ssh, scp, sftp and host with the array of $HOSTNAMES.
| How to use aliases with auto completion in oh-my-zsh? |
1,486,900,441,000 |
Today my server slowed down greatly. Most resource-consuming are - surprisingly - two shells. Two ZSH processes on TTY 0 (what does that mean?).
> ps axjf
12474 8947 16532 16532 ? -1 Sl 1000 0:34 \_ /usr/bin/xfce4
-terminal
8947 8953 16532 16532 ? -1 S 1000 0:00 | \_ gnome-pty-
helper
8947 24044 24044 24044 ? -1 Rs 1000 87:01 | \_ zsh
8947 24176 24176 24176 ? -1 Rs 1000 86:45 | \_ zsh
8947 31137 31137 31137 pts/2 2313 Ss 1000 0:00 | \_ zsh
31137 2313 2313 31137 pts/2 2313 R+ 1000 0:00 | \_ ps
Before I kill these, how to find out what are they doing?
Running:
Ubuntu 16.04.3 LTS
ZSH (version says zsh 5.1.1 (x86_64-ubuntu-linux-gnu)) with Oh-My-ZSH
Kernel, dm, etc.
inxi -S -xxx
System: Host: T420s Kernel: 4.4.0-104-generic x86_64 (64 bit gcc: 5.4.0) Desktop: Xfce 4.12.3 (Gtk 2.24.28) info: xfce4-panel dm: lightdm Distro: Ubuntu 16.04 xenial
|
Before I kill these, how to find out what are they doing?
strace them, for starters. In a pinch, use a debugger.
what does that mean?
It means that they have no controlling terminal. Given that they are children of XFCE Terminal (right there as /usr/bin/xfce4-terminal in your process tree), you should also look to the terminal emulator sessions on your GUI.
| What is this shell doing and how to find it out? |
1,486,900,441,000 |
I'm trying to setup zsh so that it autocompletes my rclone commands, for example rclone copy gdr <tab> and it becomes rclone copy gdrive-johnsmith while also doing the same thing to file names.
rclone did come with a command to generate a zsh autocomplete file, but the file did not autocomplete remote directory names (like gdrive-johnsmith: above), just the commands like copy, listremotes, and authorize. I opened up the generated file and could not for the life of me figure out how to make zsh list the remote names (which I can get a list of using rclone listremotes) and the files together "the correct way" (no parsing ls :P). Anyways, I ended up giving up and doing just that and now my _rclone file looks something like this:
#compdef rclone
_arguments \
'1: :->level1' \
'2: :->level2' \
'3: :($(rclone listremotes) $(ls))'
_arguments '*: :($(rclone listremotes) $(ls))'
The entire file is like 38 lines but I don't think there's anything relevant in there (I can post the rest if needed). The "_arguments" line used to look like this:
_arguments '*: :_files'
before I changed it to list both the remotes and files in the cwd. Like I said above, I'd like a way to be able to use _files. My current approach is ugly, breaks whenever file or folder names have a space because zsh splits em up, and it groups everything together and it looks horrible:
17:43:06 /usr/share/zsh/vendor-completions
» rclone copy
_bootctl gdrive-fakeName: _rclone
box-fakeName: _hostnamectl _sd_hosts_or_user_at_host
_busctl _journalctl _sd_outputmodes
_curl _localectl _sd_unit_files
dropbox-google-fakeName: _loginctl _systemctl
etc...
Anyways, is there a way to, in zsh:
A) Use the _files function or anything that doesn't break whenever I press spacebar to autocomplete rclone remote directories?
B) If A is not possible, is there
atleast a way to (visually) seperate the normal directories and the
rclone ones?
ZSH version is 5.1.1, OS is KDE neon 5.11, oh-my-zsh installed too.
|
From reddit:
You can use _alternative to complete two sorts of things such as
directories and rclone remotes. For example, something like:
_arguments \
'3: : _alternative
"files:file:_files"
"remotes:remote:($(rclone listremotes))"'
The space before _alternative is important here to avoid _arguments
passing compadd options to it.
Whether they are visually separated depends on your style settings. I
think oh-my-zsh does this for you but if not, try the following:
zstyle ':completion:*' group-name ''
zstyle ':completion:*:descriptions' format '%B%d%b'
Thanks to /u/okapi-a!
| zsh shell autocomplete, how to autocomplete both files and arbitrary strings returned from a function |
1,486,900,441,000 |
I use oh-my-zsh configuration. When I want to auto-complete, I need to first type correctly the initial letter. For example
go, then tab will give google-chrome. If I type *le-ch*. It didn't work. How can I do that?
|
You can get that behavior by setting the completion style completer to include the _expand control function. This is what I use:
zstyle ':completion:*' completer _expand _complete _match _prefix
| Can I auto-complete by tab in zsh with regular expression |
1,486,900,441,000 |
I'm trying to use colors in oh-my-zsh themes. It works fine on my home computer (ubuntu), but in a work computer (Scientific Linux i.e. Enterprise linux) the prompt colors are actually spelled out. For example, my prompt using the blinks theme looks like this (note this ISN'T the code, this is what appears as my prompt, except for my username and computername which I've replaced).
{black}{green}USRENAME{blue}@{cyan}COMPUTERNAME{green}
{yellow}{black}~{green} {black}{blue}±{black} %
!{cyan}1128
To see what the blinks prompt should look like, you can look at the
oh-my-zsh themes page.
|
Most likely the version of zsh you are using is from before the %F color escape sequence was added. This means that, in addition to not coloring the prompt correctly, it will leave the arguments to this sequence lying around. To solve this you should replace the current theme file with this:
function _prompt_char() {
if $(git rev-parse --is-inside-work-tree >/dev/null 2>&1); then
echo "±%{%b%}"
else
echo ' '
fi
}
ZSH_THEME_GIT_PROMPT_PREFIX=" [%{%B%}"
ZSH_THEME_GIT_PROMPT_SUFFIX="%{%b%B%}]"
ZSH_THEME_GIT_PROMPT_DIRTY=" *%{%b%}"
ZSH_THEME_GIT_PROMPT_CLEAN=""
PROMPT='%{%b%}
%{%B%}%n%{%B%}@%{%B%}%m%{%B%} %{%b%}%~%{%B%}$(git_prompt_info)%E%{%b%}
%{%}$(_prompt_char)%{%} %#%{%b%} '
RPROMPT='!%{%B%}%!%{%b%}'
| Colors not rendered correctly in oh-my-zsh themes |
1,486,900,441,000 |
I installed zsh + oh-my-zsh in an archlinux environment.
after that ls command's output became like this:
How I can change folders' color ?
|
Those "ugly" colors are caused by two things:
The use of ls's --color option
Uncommon permissions (mode bits) of the files/directories that are displayed
Remedies:
Adjust the colors to your taste by setting/changing the LS_COLORS environment variable (see ls, dircolors and dir_colors manpages)
Fix your folder permissions (there is probably something fishy, like o+w); either chmod them, or change the mount option if /d/archive is a mount point for a filesystem that does not support file permissions (e.g. FAT/VFAT)
Do not use the color option: ls is probably an alias to ls --color=auto (you can confirm this with type ls); either type ls --color=never to override it, or unalias ls, or modify your Zsh startup scripts to comment out the ls alias definition.
| Solve ugly color in ls command |
1,486,900,441,000 |
I am running Arch Linux locally. When I connect to my remote Debian 10 server via ssh, the cursor behaves in an awkward way:
As long as every command returns statuscode 0, everything is fine. When another code is returned, the cursor and the right prompt are shifted to the left by 2 characters, as shown below. The first prompt is normal, the second after pressing Ctrl+C:
----|---------------------------------
~ » user@hostname
--|-----------------------------------
~ » 130 ↵ user@hostname
I have manually changed the line of dashes afterwards to show where the cursor is: below the |. I am in fact overriding the » when I start typing a command.
When I then try to use a command from history and change it, I change it at a different character than is shown on the screen, which is quite confusing and annoying.
After the next command that returned statuscode 0, the cursor is normal again.
This seems to be happening accross terminals (I tried in the console and using Alacritty and URXVT).
I am using the "af-magic" - theme. When I switch to another theme that does not show status codes, the problem disappears. It is the same though for other themes that do show the statuscode (e.g. "smt"). So something about the statuscode display seems to be causing the issue.
My .zshrc is the same both locally and remotely. Locally, I don't have that problem.
HISTSIZE=1000000
SAVEHIST=1000000
HISTFILE=~/.cache/zsh/history
## oh my zsh
export ZSH="$HOME/.config/zsh/oh-my-zsh"
ZSH_THEME="af-magic"
plugins=(
git vi-mode zsh-autosuggestions history-substring-search
)
ZSH_DISABLE_COMPFIX="true"
source $ZSH/oh-my-zsh.sh
## Load aliases
[ -f "${XDG_CONFIG_HOME:-$HOME/.config}/shell/aliasrc" ] && source "${XDG_CONFIG_HOME:-$HOME/.config}/shell/aliasrc"
## vim mode config
# ---------------
bindkey -M vicmd 'k' history-substring-search-up
bindkey -M vicmd 'j' history-substring-search-down
# Activate vim mode.
bindkey -v
# autosuggest config
ZSH_AUTOSUGGEST_HIGHLIGHT_STYLE="fg=#3a3a3a"
bindkey '^ ' autosuggest-accept
# Remove mode switching delay.
KEYTIMEOUT=5
# Change cursor shape for different vi modes.
function zle-keymap-select {
if [[ ${KEYMAP} == vicmd ]] ||
[[ $1 = 'block' ]]; then
echo -ne '\e[1 q'
elif [[ ${KEYMAP} == main ]] ||
[[ ${KEYMAP} == viins ]] ||
[[ ${KEYMAP} = '' ]] ||
[[ $1 = 'beam' ]]; then
echo -ne '\e[5 q'
fi
}
zle -N zle-keymap-select
_fix_cursor() {
echo -ne '\e[5 q'
}
precmd_functions+=(_fix_cursor)
Any tips on how to solve this?
|
My locale was not set. I set it now, and it works!
| zsh-cursor displacement over ssh |
1,565,492,070,000 |
I want to change my PATH variable in zsh.
Problem: I don't understand where in the .zshrc file I have to make modifications.
Normally, I would look for the assignment to the PATH variable and set the values from scratch how I would like them to be (leaving all the systems binaries directories untouched).
The first lines in my .zshrc file are as follows:
# If you come from bash you might have to change your $PATH.
# export PATH=$HOME/bin:/usr/local/bin:$PATH
# Path to your oh-my-zsh installation.
export ZSH="/Users/Sam/oh-my-zsh"
export PATH=$PATH:/Applications/Postgres.app/Contents/Versions/13/bin
etc.
My actual PATH variable is:
/Library/Frameworks/Python.framework/Versions/3.9/bin:/Library/Frameworks/Python.framework/Versions/3.8/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Applications/Postgres.app/Contents/Versions/13/bin
I want to delete the directory where python3.8 is in, it's redundant.
My questions:
Do I have to change line 2 or line 7 in my .zshrc file?
Line 2 is commented out...is it executed anyway at the start of the terminal?
I have tried to comment out line 7. But the postgres directory still remained in my PATH variable which I don't understand.
|
Re-posting from comments in to an answer, but with some extra notes.
First, search the web for introductory guides to working with the Un*x shell (command line) and terminal sessions. Most of them give a lot of information on the most common environment variables, such as PATH. (Some may not give a lot of detail on the many places the PATH variable is set/modified/etc, however.)
Second, understand that environment variables are per instance, meaning, every process gets it's own copy of the variable (from the parent process) when it is started, and there is no such thing as a "global environment". You can see this if you open two terminal instances, and in one, type export PATH="", clearing the PATH variable, and then in the other terminal, type echo $PATH. You will see that the PATH variable in the second was not affected by the clearing in the first terminal window.
Third, try to avoid asking multiple questions in one question, unless the questions are all very closely related.
I will be jumping back and forth here between the questions asked (since they are very closely related). Also, I often use bash syntax/commands. Different shells might use other forms (such as setvar in tcsh).
Your default .zshrc file is copied from the skeleton (template) files when your user home directory ($HOME) is created (usually when your user record is created -- and keep in mind if your SysAdmin modifies the skel files, the new version does NOT get copied in to your already existing home directory!). These skeleton files are typically located in places like /etc/skel, and other places may be defined for specific shells, or by your system administrator.
These default/skeleton files often include samples of common usages, sometimes commented out (prefixing it with a "#"), so when you edit them in your user home directory, you can uncomment or edit them however you like or need.
Keep in mind that not all these files get loaded automatically. They only get loaded when you "log in"--Some might only get loaded when you log in via the GUI, while others only get loaded when you log in to a text-mode console. Commonly, different shells use a name such as .<shell>rc, such as .bashrc or .zshrc--which are often just simply called "rc files"--to define the default configuration when you log in to/start that shell. Note especially that this means any commands or variables set in your rc files are not available if you execute a process from something like a cron job or a GUI launcher that does not load the shell and it's rc file.
Also keep in mind that the shell does not automatically reload rc files every time you edit them. To "reload" them after editing them, you either need to source .zshrc (or source .bashrc, etc), or close/exit the shell/terminal and log back in. Some shells can force a session reload, you will have to read your shell's man page for how to do that.
When you use the source .zshrc method, you also need to remember that previous settings and values are kept. That means, unless your rc file explicitly clears the PATH variable, it will continue to contain the previous value and add anything added by the rc file--even if a previous load of the rc file already added it. For example, put the following code in a file named "growvar.sh":
export GROWVAR="$GROWVAR:Grow!"
echo "GROWVAR now contains \"$GROWVAR\""
And save it. Then note the following commands and results:
$ source growvar.sh
GROWVAR now contains ":Grow!"
$ source growvar.sh
GROWVAR now contains ":Grow!:Grow!"
$ source growvar.sh
GROWVAR now contains ":Grow!:Grow!:Grow!"
(Also note that you need to source it: Setting the file to executable (chmod +x ...) will not do as you expect because it will "execute" in a sub-shell without affecting the parent shell process environment.)
This is usually harmless for the PATH, since most shells skip checking each part of the $PATH it has already checked. They also ignore "empty" paths, such as "::" (which is actually three empty paths separated by ":"s). This is why `export PATH="$PATH:/new/path/here" will still work even if $PATH was not previously set. If you add a lot of long paths to the PATH variable, however, it may grow very large with multiple and redundant paths. (And may even run ou of free environment space memory.)
I am certain I am forgetting something... But here is how it all ties together:
Question #1: Change line #7 -- OR.. simply comment it out and add a "corrected" version. This way, in the future, you can immediately see that you changed it, what it was before the change, and what it is after the change. Do the same for commented out "sample" code from the skeleton files. Do not uncomment them: copy the code, adjust it to your liking, and uncomment the copy.
Question #2: As indicated by the above, the "#" makes the line a comment line, which is simply ignored by the shell.
Question #3: Most likely, you expected that either changing the rc file automatically reloaded it (which I explained above it does not do), or if you did reload (via the source command), you expected the PATH to be cleared of it's current value (which I also explained above is not the case). You need to completely restart/reload the shell to get the changes.
Question (from comments) #1: "Where does it get $PATH from?" It depends. Initially, PATH does not even exist. If you try to reference it, as in $PATH, it simply returns an empty string (""). Once you log in to your shell, the shell will automatically source a number of system default files, typically in /etc/default (and other places, your shell's man page will give you detailed specifics of your shell), which set up the PATH variable for further use. That is why most sample PATH settings use export PATH="$PATH:/new/path/here", so they can preserve any previously set paths (or none at all if PATH did not previously exist).
Question (from comments) #2: Regarding the sample line about "$HOME/bin": Many experienced Un*x users have their own $HOME/bin directory to provide custom commands and overrides specific to their login. Thus, the sample configuration line demonstrates this by adding the directory to the PATH. Any non-existent directories in the PATH variable are simply ignored and skipped without error.
Edit to add: Oh, also... In the extreme edge case of $HOME not being defined, it simply gets replaced by an empty string the same way PATH does. So, "$HOME/bin" evaluates to "/bin".
Another "Edit to add" something to further help: If your goal is to to simply clean up the PATH, you can write a simple utility to do so -- but you have to remember that the utility can only modify it's own copy of PATH. You can work around this by having the utility output (on stdout) the cleaned up path, which the parent process/shell can read to set the new path. For example:
...
export PATH=`/bin/mypathutil --cleanup`
...
I actually have a TCL script, /bin/cleanpath which outputs a path where every directory is only given once. So something like "/bin:/bin:/usr/bin:/bin:/usr/bin:/usr/games:/bin:/bin" would output simply "/bin:/usr/bin:usr/games". (Technically, my script does slightly more, such as assuring my special custom directory, /usr/local/overrides, is always first in PATH so I can always put custom command overrides there. This way, I can also temporarily disable some commands by creating symlinks in /usr/local/override that simply point to /bin/true. (This will probably not work for shell built-ins, however, or programs which use a full pathname to the executable file...)
| Changing PATH Variable in zsh |
1,565,492,070,000 |
I need to set up a function in zsh that would edit a different file based on some input at the command line.
I want to simplify my aliases so I don't have multiple aliases to do the same thing but with a slight variation. I am specifically trying to set up a function to open in my editor different versions of the php.ini file (for php 5.4, 5.5, 5.6 and 7.0)
Right now, I have defined the following aliases:
alias editphpini54="subl /usr/local/etc/php/5.4/php.ini"
alias editphpini55="subl /usr/local/etc/php/5.5/php.ini"
alias editphpini56="subl /usr/local/etc/php/5.6/php.ini"
alias editphpini70="subl /usr/local/etc/php/7.0/php.ini"
What I would like to do is set up a function called editphpini and then input a variable (version number) and have it intelligently open up the right file. This could then be future-proof as well, as long as the basic path remains the same.
So, what I want to do be able to type in
editphpini 54
And have the function parse that command and load the php.ini file located in /usr/local/etc/php/5.4/php.ini
Using the above example, I would then be able to substitute 55 56 or 70 at the end of the command and that would issue the relevant command.
In my thoughts, the function would take the XX version number, insert it into the command subl /usr/local/etc/php/X.X/php.ini using the XX to define the version number.
Honestly, I have tried multiple things, and nothing seems to work, so rather than just list all my failed attempts, I'd appreciate if someone could point me in the right direction.
Thank you,
Ali
|
function editphpini() {
local version=$( echo $1 | sed 's/^\(.\)/\1./' )
subl /usr/local/etc/php/${version}/php.ini
}
usage:
% editphpini 54
| ZSH function to edit a file based on an input at the cli |
1,565,492,070,000 |
How do i get this fancy "path bar with git icons" as shown in this picture of zsh?
What is it called?
|
This is a Zsh theme called agnoster, which works in conjunction with Powerline-patched fonts to display those symbols.
It’s available in Oh My Zsh.
| How do i get this fancy "path bar with git icons" as shown in this picture of zsh |
1,565,492,070,000 |
I was trying to use an alias which should run two commands, where the first is fine to be run with normal user privileges and the second one needs sudo privileges.
alias hosts-get="scp [email protected]:/etc/hosts /tmp/ && sudo cat /tmp/hosts >> /etc/hosts"
The usecase is to pull the hosts file of a remote server and then append it to the hosts file on my own computer (the remote server contains all the IP to domain information of client systems).
However, when running the alias I get zsh: permission denied: /etc/hosts, so it looks like the sudo is being ignored or rather zsh can't interpret it or something.
After some searching around I changed the alias to this:
alias hosts-get="scp [email protected]:/etc/hosts /tmp/ && cat /tmp/hosts | sudo tee -a /etc/hosts"
This looks to work correctly. Can someone please explain the background of this?
|
While the sudo command in your first alias provides root privileges for cat /tmp/hosts the redirection >> /etc/hosts will be tried with your user privileges.
As those usually are not high enough you get the 'permission denied' error.
To make this work, you can run the command in a subshell like this:
alias hosts-get="scp [email protected]:/etc/hosts /tmp/ && sudo sh -c \"cat /tmp/hosts >> /etc/hosts\""
or just do it the way you did it with your second approach.
Here you redirect the output of the 'unprivileged' cat command into the privileged 'tee' command which then has the right to append the information to /etc/hosts.
| Having sudo and non-sudo parts in an alias - why does it not work with >>? |
1,565,492,070,000 |
I have installed oh-my-zsh on high Sierra but cannot uninstall and return my terminal to standard bash.
I have used uninstall_oh_my_zshcommand, but still can see .zsh on terminal once open it!
can anyone help?
|
You should change your terminal to bash first using /usr/bin/chsh -s /bin/bash , then simply remove all zsh related files. Or use this Script to run it simply navigate to the script directory and do sh uninstall.sh
| remove oh-my-zsh |
1,565,492,070,000 |
I'm using zsh 5.0.2 (x86_64-apple-darwin12.3.0) on the latest MacOSX. If it makes any difference, I have also enabled oh-my-zsh.
The shell seems to be missing the .zshrc file when I want to source it.
The result of the execution of the following commands should expose my problem clearly. (~ » is my prompt).
The file exists
~ » ls -l .zshrc
-rw-r--r-- 1 user staff 1882 May 16 10:43 .zshrc
~ » [[ -r .zshrc ]] && echo "Exists"
Exists
The file isn't read by "."
~ » . .zshrc
.: no such file or directory: .zshrc
I don't know what causes this behavior, especially that this works
~ » . "$(pwd)"/.zshrc
Success!
My question is:
Why won't . .zshrc work?
|
The . command searches for the file in your $path, it does not by default search in the current directory. That is why it works when you give the absolute path ("$(pwd)"/.zshrc).
From the zsh manual about the . command:
. file [ arg ... ]
Read commands from file and execute them in the current shell environment.
If file does not contain a slash, or if PATH_DIRS is set, the shell looks in the components of $path to find the directory containing file. Files in the current directory are not read unless ‘.’ appears somewhere in $path.
...
Compare to the source command:
source file [ arg ... ]
Same as ‘.’, except that the current directory is always searched and is always searched first, before directories in $path.
| Weird behavior when sourcing .zshrc |
1,565,492,070,000 |
I'm trying to limit the column width of the command column when running a ps command, but also trying to pipe that output into a grep command. However, this is not working.
This runs fine:
ps -eo pid,user,command:30
However, this:
ps -eo pid,user,command:30 | grep node
gives me this error:
ps: command:30: keyword not found
I'm actually running oh-my-zsh on a Mac in case that matters.
All help is appreciated; thanks!
|
Assuming sed supporting -E, limiting command to 30 characters:
ps -eo pid,user,command |
sed -E 's/^( +[^ ]+ +[^ ]+ +)(.{30}).*$/\1\2/g'
using awk, pid column formatted to width 6 (assuming the pid will have at most 6 digits), user column formatted to width 10, command to 30:
ps -eo pid,user,command |
awk '{
line=$0;
sub(/^ +[^ ]+ +[^ ]+ +/, "", line);
printf("%6s %s%*s %s\n", $1, substr($2, 0, 10),
length($2) <= 10 ? 10-length($2) : 0, " ",
substr(line, 0, 30));
}'
| Using grep with ps and column width specification |
1,565,492,070,000 |
I just installed oh-my-zsh. Things worked fine. Then I tried commenting out export ZSH="~/.oh-my-zsh"
After this, when I uncommented the line back, I keep getting the below error. However, "oh-my-zsh.sh" is present
(base) abc@def-MacBook-Pro .oh-my-zsh % source $ZSH/oh-my-zsh.sh
source: no such file or directory: ~/.oh-my-zsh/oh-my-zsh.sh
(base) abc@def-MacBook-Pro .oh-my-zsh % ls -l ~/.oh-my-zsh/oh-my-zsh.sh
-rwxr--r-- 1 abc staff 5927 Feb 11 2022 /Users/abc/.oh-my-zsh/oh-my-zsh.sh
|
That's because ~ is not expanded to the value of the $HOME variable when you quote it (with any type of quoting mechanism including single, double quotes, backslash, $'...').
Thus you can use these commands instead:
export ZSH=~"/.oh-my-zsh"
or
export ZSH=~/.oh-my-zsh
or
export ZSH="$HOME/.oh-my-zsh"
Note that normally, ~ is not expanded after = either:
$ echo x=~
x=~
unless the magicequalsubst option is enabled:
$ set -o magicequalsubst
$ echo x=~
x=/home/me
But they are expanded in assignments:
$ x=~
$ echo "$x"
/home/me
And in relatively recent versions of zsh, export and other variable assignment builtins are treated as dual builtin / keywords, and their arguments are parsed as assignment.
| oh-my-zsh No such file or directory even after installation |
1,565,492,070,000 |
I just installed ZSH on a remote server where we are 2 "admins".
I switched my default shell to ZSH with chsh -s $(which zsh). echo $SHELL gives the output /usr/bin/zsh which proves it.
But, when I open my ssh session I receive an error like:
/etc/profile.d/vk.sh:30: command not found: shopt
This error appears only at startup and I see it only once when opening an ssh session.
In my understanding, the other admin placed some custom script with his own aliases and using shopt -s histappend command there as well.
My question is, why my SSH ZSH session invoking that script at startup?
Shouldn't it be scoped just to my profile?
What would be a graceful solution for me to run ZSH without affecting/touching his stuff? Should I ask him to move that thing somewhere else in his home dir?
|
The /etc/profile file contains system wide profile settings. Within that file, many distributions are sourcing scripts within /etc/profile.d. Hence, all interactive logins will invoke what is in that folder. If you want a profile script to be scoped to one account, you have to either
move that script into ~/.profile or ~/.bash_profile (for bash users), or
add login in the vk.sh to skip execution based on the logged in user.
| Multi-user env, SSH ZSH - command not found: shopt |
1,565,492,070,000 |
I'd like to connect to a remote server using ssh and have the session running in Vi mode. I have found how to do that for bash:
ssh username@server -t 'bash -o vi'
But I need the same thing for zsh (oh-my-zsh, if that makes any difference). I can't find anywhere how to achieve this. I have tried "zsh -o vi" but that didn't work. Once I figure out the correct command I will just create a shortcut script that would ssh me to the server and set the editing mode to Vi.
Please, don't advise modifying configuration files on the server, I am one of the many users who use the server and unfortunately we use the same account, so it's important that the session is only run in Vi mode for me but not for other users. Thank you very much for any suggestions!
The content of my ~/.zshrc on the remote server (with all comments removed):
export ZSH="/root/.oh-my-zsh"
ZSH_THEME="risto"
plugins=(
git
ruby
gem
rails
)
source $ZSH/oh-my-zsh.sh
It's pretty much the standard zshrc of oh-my-zsh. I've probably only changed the default theme and added one or two plugins.
And below is the content of /root/.oh-my-zsh/oh-my-zsh.sh, if it can be helpful:
# Set ZSH_CACHE_DIR to the path where cache files should be created
# or else we will use the default cache/
if [[ -z "$ZSH_CACHE_DIR" ]]; then
ZSH_CACHE_DIR="$ZSH/cache"
fi
# Migrate .zsh-update file to $ZSH_CACHE_DIR
if [ -f ~/.zsh-update ] && [ ! -f ${ZSH_CACHE_DIR}/.zsh-update ]; then
mv ~/.zsh-update ${ZSH_CACHE_DIR}/.zsh-update
fi
# Check for updates on initial load...
if [ "$DISABLE_AUTO_UPDATE" != "true" ]; then
env ZSH=$ZSH ZSH_CACHE_DIR=$ZSH_CACHE_DIR DISABLE_UPDATE_PROMPT=$DISABLE_UPDATE_PROMPT zsh -f $ZSH/tools/check_for_upgrade.sh
fi
# Initializes Oh My Zsh
# add a function path
fpath=($ZSH/functions $ZSH/completions $fpath)
# Load all stock functions (from $fpath files) called below.
autoload -U compaudit compinit
# Set ZSH_CUSTOM to the path where your custom config files
# and plugins exists, or else we will use the default custom/
if [[ -z "$ZSH_CUSTOM" ]]; then
ZSH_CUSTOM="$ZSH/custom"
fi
is_plugin() {
local base_dir=$1
local name=$2
test -f $base_dir/plugins/$name/$name.plugin.zsh \
|| test -f $base_dir/plugins/$name/_$name
}
# Add all defined plugins to fpath. This must be done
# before running compinit.
for plugin ($plugins); do
if is_plugin $ZSH_CUSTOM $plugin; then
fpath=($ZSH_CUSTOM/plugins/$plugin $fpath)
elif is_plugin $ZSH $plugin; then
fpath=($ZSH/plugins/$plugin $fpath)
else
echo "[oh-my-zsh] plugin '$plugin' not found"
fi
done
# Figure out the SHORT hostname
if [[ "$OSTYPE" = darwin* ]]; then
# macOS's $HOST changes with dhcp, etc. Use ComputerName if possible.
SHORT_HOST=$(scutil --get ComputerName 2>/dev/null) || SHORT_HOST=${HOST/.*/}
else
SHORT_HOST=${HOST/.*/}
fi
# Save the location of the current completion dump file.
if [ -z "$ZSH_COMPDUMP" ]; then
ZSH_COMPDUMP="${ZDOTDIR:-${HOME}}/.zcompdump-${SHORT_HOST}-${ZSH_VERSION}"
fi
if [[ $ZSH_DISABLE_COMPFIX != true ]]; then
source $ZSH/lib/compfix.zsh
# If completion insecurities exist, warn the user
handle_completion_insecurities
# Load only from secure directories
compinit -i -C -d "${ZSH_COMPDUMP}"
else
# If the user wants it, load from all found directories
compinit -u -C -d "${ZSH_COMPDUMP}"
fi
# Load all of the config files in ~/oh-my-zsh that end in .zsh
# TIP: Add files you don't want in git to .gitignore
for config_file ($ZSH/lib/*.zsh); do
custom_config_file="${ZSH_CUSTOM}/lib/${config_file:t}"
[ -f "${custom_config_file}" ] && config_file=${custom_config_file}
source $config_file
done
# Load all of the plugins that were defined in ~/.zshrc
for plugin ($plugins); do
if [ -f $ZSH_CUSTOM/plugins/$plugin/$plugin.plugin.zsh ]; then
source $ZSH_CUSTOM/plugins/$plugin/$plugin.plugin.zsh
elif [ -f $ZSH/plugins/$plugin/$plugin.plugin.zsh ]; then
source $ZSH/plugins/$plugin/$plugin.plugin.zsh
fi
done
# Load all of your custom configurations from custom/
for config_file ($ZSH_CUSTOM/*.zsh(N)); do
source $config_file
done
unset config_file
# Load the theme
if [[ "$ZSH_THEME" == "random" ]]; then
if [[ "${(t)ZSH_THEME_RANDOM_CANDIDATES}" = "array" ]] && [[ "${#ZSH_THEME_RANDOM_CANDIDATES[@]}" -gt 0 ]]; then
themes=($ZSH/themes/${^ZSH_THEME_RANDOM_CANDIDATES}.zsh-theme)
else
themes=($ZSH/themes/*zsh-theme)
fi
N=${#themes[@]}
((N=(RANDOM%N)+1))
RANDOM_THEME=${themes[$N]}
source "$RANDOM_THEME"
echo "[oh-my-zsh] Random theme '$RANDOM_THEME' loaded..."
else
if [ ! "$ZSH_THEME" = "" ]; then
if [ -f "$ZSH_CUSTOM/$ZSH_THEME.zsh-theme" ]; then
source "$ZSH_CUSTOM/$ZSH_THEME.zsh-theme"
elif [ -f "$ZSH_CUSTOM/themes/$ZSH_THEME.zsh-theme" ]; then
source "$ZSH_CUSTOM/themes/$ZSH_THEME.zsh-theme"
else
source "$ZSH/themes/$ZSH_THEME.zsh-theme"
fi
fi
fi
|
Once inside your shell, simply run
bindkey -v
Directly from ssh:
ssh -t username@server 'VISUAL=vi zsh'
| Run zsh (oh-my-zsh) in Vi mode when connecting to remote server via ssh |
1,565,492,070,000 |
Seems like history [number] is backward in zshell because it's using fc. How do I get history [number] to behave like it does in bash?
➜ exec bash
bash-3.2$ history 3
35 history 5
36 exit
37 history 3
bash-3.2$
➜ history 3
1 pwd
2 ..
3 mv work Documents
➜ history
3133 history 5
3134 exec bash
3135 history
3136 history 3
3137 history -3
3138 history 20
So in bash it behaves like I'd expect: last 3 commands. But in zshell it's backwards: the first 3 history commands. This is annoying and I'd like to fix it.
Closest I've got so far:
function history {
fc -l -$1
}
But that still produces history starting at 1 instead of the last entry.
Related: Show older or newer history items with the history command in zsh
|
It wasn't as difficult as I thought it would be. Added this to my ~/.profile
# zshell aliases history to "fc -l"
# quick version
alias h="fc -l -50" # last 50
# history searching
function hg {
echo "Searching for '$1'..."
fc -l 0 | grep "$1"
}
Related and helpful: Show older or newer history items with the history command in zsh
| How do I alias history 20 to work the same way in zshell vs. bash? |
1,565,492,070,000 |
I want an alias shortcut to achieve the following:
Clone a github repository with a custom folder name
Open it in my fav text editor (atom)
I currently use this inside ~/.zshrc:
alias quickstart="git clone https://github.com/myname/quickstart-html-template.git new_html_project && atom new_html_project"
Can I parameterize new_html_project?
|
You can't define parameters in an alias, you need to use a function:
quickstart() {
git clone https://github.com/myname/quickstart-html-template.git "$1" && atom "$1"
}
Add that to your .zshrc instead of the alias definition.
| Using zsh alias to quickly clone a git repository with custom folder name |
1,565,492,070,000 |
When I type time + number in zsh:
# atupal at local in /tmp/atupal/setup/bin [10:01:49]
$ time 1
/tmp/atupal/setup/bin/lib/python2.7
# atupal at local in /tmp/atupal/setup/bin/lib/python2.7 [10:01:54]
$ time 2
/tmp/atupal/setup
# atupal at local in /tmp/atupal/setup [10:01:59]
$ time 3
/tmp/atupal/setup/app
# atupal at local in /tmp/atupal/setup/app [10:02:03]
$ time 3
/tmp/atupal/setup/bin
# atupal at local in /tmp/atupal/setup/bin [10:02:04]
$ time 3
/tmp/atupal/setup/bin/lib/python2.7
# atupal at local in /tmp/atupal/setup/bin/lib/python2.7 [10:02:05]
$
But when I type time 10 is says command not found: 10
My zsh version is :zsh 5.0.2-4
And my uname result:Linux 3.12.5-1-ARCH #1 SMP PREEMPT Thu Dec 12 12:57:31 CET 2013 x86_64 GNU/Linux
|
oh-my-zsh creates a few alias in .oh-my-zsh/lib/directories.zsh named 1, 2 ... 9 which expand to cd -, cd -1, etc. So time is functioning correctly, but the unexpected alias 1 actually does something. The reason why time's normal output isn't given is due to the fact cd is a builtin command that doesn't require forking.
| zsh: What does the command "time + number" do in zsh |
1,565,492,070,000 |
I want to clear my shell history on every shutdown/logout.
I know how to clear the history manually, I know how to clear the history automatically, when closing the session/terminal emulator. However, this is not the intended behaviour.
I am using zsh on manjaro with wayland and sway.
I have tried using .zlogout. However, this did not work, as far as I understand, because it is ment for login shells (I don't know what makes a login shell).
|
If you happen to use systemd (which manjaro should AFAIK), one option would be a simple service that just succeeds and has the history-deletion executed when it stops. Then make it depend on default.target:
[Unit]
Description=Delete zsh-history on logout/shutdown
[Service]
Type=oneshot
RemainAfterExit=true
ExecStart=/bin/true
ExecStop=/home/grbll/bin/zsh-remover.sh
[Install]
WantedBy=default.target
User services go e.g. in ~/.config/systemd/user/zsh-history-wipe.service
For enabling it permanently and for activating it for your current session once run
systemctl --user enable zsh-history-wipe
systemctl --user start zsh-history-wipe
As all services are stopped with the last logout or on shutdown, the ExecStop-command will be run in the end. Obviously does not work for e.g. power outages.
Note that lingering must be disabled for the user!
| Clear shell history on shutdown/logout |
1,565,492,070,000 |
I recently switched from bash to zsh in Fedora 38.
I have installed oh my zsh and have the following plugins.
plugins=(git fzf tig zsh-autosuggestions)
My terminal has been acting really weird. Part of it will disappear if I press up on the key pad and it has strange glitches when I paste stuff in with the middle mouse button.
Also when deleting a command by using backspace part of it will remain on the terminal but will have no influence over the new command I put in. (see picture 2 I cannot delete the oc lo but it acts as if I am at the start of the prompt so ls --help runs successfully)
I have some screenshots below showing some of the weird glitches.
For context I am using Terminology as my main terminal but I experience these issues with Konsole as well.
Is this an issue common with oh my zsh?
My primary prompt is defined as:
$ typeset PROMPT
PROMPT='[%n]$fg[blue][%m]%{$fg[white]%}$(git_custom_status)[%~% ]%{$reset_color%}%B$%b '
|
In your:
PROMPT='[%n]$fg[blue][%m]%{$fg[white]%}$(git_custom_status)[%~% ]%{$reset_color%}%B$%b '
While $fg[white] and $reset_color which presumably are the escape sequences that tell the terminal to change the foreground colour to white and reset the colours as defined by the colors autoloadable function are within %{...%} to tell zsh's line editor that those characters have zero-width on display, that's not the case of $fg[blue].
$ autoload colors
$ colors
$ echo $#fg[blue]
5
That's a 5-character long sequence, but when sent to the terminal it only changes the foreground colour and doesn't move the cursor five columns to the right, but as you didn't tell it that, the line editor gets a misunderstanding of where the cursor is meant to be which shows when you try to move the cursor around for instance.
Here, while you could use %{...%} around that $fg[blue] as well, in prompt expansion you don't need that. Prompt expansion has special directives to change the foreground and background colours: %F{colour} and %K{colour} (and %f and %k to reset to the default), so it should just be:
PROMPT='[%n]%F{blue}[%m]%F{white}$(git_custom_status)[%~]%f%B$%b '
That also assumes the promptsubst option is enabled and that the git_custom_status command outputs something that is a valid prompt string.
| Experiencing glitches on terminal Fedora 38 |
1,565,492,070,000 |
I tried to change the default zsh theme with oh-my-zsh from their github repository and I just edited .zshrc switching from the default theme to another one and it just somehow went wrong cause now I can't switch anymore and the theme stays the same even tho I'm switching to new ones.
I just wanna go back to the regular out of the box zsh theme that's in Kali. Can someone help me? (I'd prefer the easy way cause I'm not an adavnced linux user, yet). Thanks a lot!
|
If you're not an advanced user, beware that Kali does a whole load of things differently to usual. This is because it's targeted at experienced security professionals. That said, you should be able to get a fresh copy of .zshrc from the template directory /etc/skel
| Get back to default zsh theme in kali linux |
1,565,492,070,000 |
I am using zsh with oh my zsh and I wanted to get a thing like this:
How can I do it? I want a setting to put somewhere, so that whenever I restart my terminal and my system, it always displays the way a set it.
Thanks in advance.
|
PS1='%B%F{#ff1000}[%F{#d0b000}%n%F{#80f000}%b@%B%F{#00c0c0}%m %F{#ff80a0}%~%F{#ff1000}]%f%b$ '
Gives similar colour shades. Adapt to your taste.
%B: bold (%b reverts to non-bold)
%F{#RRGGBB} foreground colour specified with levels of red/green/blue in hexadecimal. (%f reverts to default colour). If your terminal doesn't support true-colour specifications but supports a 88 or 256 colour palette, run zmodload zsh/nearcolor.
%n user name
%m machine name (without domain part)
%~ current working directory with tilde representation where applicable.
See info zsh 'prompt expansion' for details.
| Customizing hostname in zsh prompt |
1,565,492,070,000 |
In my ZSH custom config, I have this function:
cll() { ls -AlhG "$@" | awk '{k=0;for(i=0;i<=8;i++)k+=((substr($1,i+2,1)~/[rwx]/)*2^(8-i));if(k)printf(" %0o ",k);print}'; }
It outputs:
➜ test cll
total 32
644 -rw-r--r-- 1 work admin 0B Oct 7 18:55 .hidden
644 -rw-r--r-- 1 work admin 480B Aug 22 2016 gulpfile.js
644 -rw-r--r-- 1 work admin 149B Jan 7 2017 index.php
755 drwxr-xr-x 247 work admin 8.2K Aug 22 2016 node_modules
644 -rw-r--r-- 1 work admin 1.0K Aug 22 2016 test.less
644 -rw-r--r-- 1 work admin 664B Aug 22 2016 test.min.css
755 -rwxr-xr-x 1 work admin 0B Oct 7 18:54 try
It also supports colors, so my executable files and such have pretty colors :)
I want to remove the permissions breakdown column (ex: -rw-r--r--) from it. So I want it to look like this:
644 1 work admin 0B Oct 7 18:55 .hidden
644 1 work admin 480B Aug 22 2016 gulpfile.js
644 1 work admin 149B Jan 7 2017 index.php
755 247 work admin 8.2K Aug 22 2016 node_modules
644 1 work admin 1.0K Aug 22 2016 test.less
644 1 work admin 664B Aug 22 2016 test.min.css
755 1 work admin 0B Oct 7 18:54 try
I have tried to mess with it, but everything I do, it breaks it. I am open to a completely different method (not piping through awk).
Final Solution:
Thank's to @Skaperen for bringing cut to my attention. I double piped the function and it worked great! Here is the output now:
➜ test cll
total
644 work admin 0B Oct 7 18:55 .hidden
644 work admin 480B Aug 22 2016 gulpfile.js
644 work admin 149B Jan 7 2017 index.php
755 work admin 8.2K Aug 22 2016 node_modules
644 work admin 1.0K Aug 22 2016 test.less
644 work admin 664B Aug 22 2016 test.min.css
755 work admin 0B Oct 7 18:54 try
Here is the function from my aliases.zsh (config in custom):
cll() { ls -AlhG "$@" | awk '{k=0;for(i=0;i<=8;i++)k+=((substr($1,i+2,1)~/[rwx]/)*2^(8-i));if(k)printf(" %0o ",k);print}' | cut -c 1-5,21-; }
The only thing that would make this perfect, is if I could add a custom column to parse whether it is a "Directory", "File", "Symbolic Link", etc.
|
Pipe it through the command cut -c 1-3,14-. tweak the numbers if you need to adjust it. Do man cut for more details.
| How to remove directory permissions from ls command piped through awk? [closed] |
1,565,492,070,000 |
When I use OMZ, I have a very, very nice feature I like to call context-sensitive history. It's easier to show than describe. If I run:
% abc
% cba
And then I type % a[up], without CS history I get% cba. With it I get % abc. What in OMZ causes this?
EDIT: I want this to give me results based on the beginning of the command. With the substring search suggested by @Thomas Dickey, it matches if what I typed was anywhere in the command.
EDIT 2: @jasonwryan's answer in How can I search history with what is already entered at the prompt in zsh? is almost it; the only thing is that the cursor should be at the end of the new line rather than staying at its current location.
|
That sounds like zsh-history-substring-search, which according to the webpage is inspired by the fish shell (and offhand sounds like the way vi-like-emacs implements command history — there are probably several variations).
For other possibilities, see @jasonwryan's answer in How can I search history with what is already entered at the prompt in zsh?
| Context-Sensitive History [duplicate] |
1,565,492,070,000 |
Any command I run (aside from clear) results in a double zsh prompt -- the first one showing the unformatted prompt, the second one showing the correct, formatted prompt.
My ~/.zshrc file:
if [[ -r "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh" ]]; then
source "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh"
fi
export ZSH="$HOME/.oh-my-zsh"
ZSH_THEME="agnoster"
zstyle ':omz:update' mode auto # update automatically without asking
ENABLE_CORRECTION="true"
COMPLETION_WAITING_DOTS="%F{yellow}waiting...%f"
HIST_STAMPS="mm/dd/yyyy"
plugins=(
zsh-completions
git
pip
jsontools
dotenv
)
source ~/powerlevel10k/powerlevel10k.zsh-theme
# To customize prompt, run `p10k configure` or edit ~/.p10k.zsh.
[[ ! -f ~/.p10k.zsh ]] || source ~/.p10k.zsh
[ -f ~/.fzf.zsh ] && source ~/.fzf.zsh
export FZF_DEFAULT_OPTS='-height=40% -preview="cat {}" -preview-window=right:60%:wrap'
alias ip="ipconfig getifaddr en0"
alias zshconf="vim ~/.zshrc"
alias szsh="source ~/.zshrc"
alias ohmyzsh="cd ~/.oh-my-zsh"
alias gs="git status"
alias gac="git add . && git commit -am"
alias gb="git branch --show-current"
alias goof="git add --all && git commit --amend --no-edit"
alias ff="find . | grep "
alias ft="grep -lrni -e "
alias rando="openssl rand -base64 24"
fpath+=${ZSH_CUSTOM:-${ZSH:-~/.oh-my-zsh}/custom}/plugins/zsh-completions/src
source ~/.zsh/zsh-autosuggestions/zsh-autosuggestions.zsh
source $ZSH/oh-my-zsh.sh
[[ -s "/Users/<user>/.gvm/scripts/gvm" ]] && source "/Users/<user>/.gvm/scripts/gvm"
Any help is appreciated. Thanks!
Output from command: typeset -p PS1 RPS1; typeset -fp precmd preexec $precmd_functions $preexec_functions
typeset PS1=$'${$((_p9k_on_expand()))+}%{${_p9k__raw_msg-}${_p9k__raw_msg::=}%}${(e)_p9k_t[7]}${_p9k__1-${${:-${_p9k__d::=0}${_p9k__rprompt::=${_p9k__1r-${${:-${_p9k__bg::=NONE}${_p9k__i::=0}${_p9k__sss::=${(Q)${:-"%\\\\{%\\\\}"}}}}+}${${:-"${${(%):-%j}:#0}"}:+${${:-${P9K_CONTENT::=""}${_p9k__n::=}${${${_p9k__bg:-0}:#NONE}:-${_p9k__n::=12}}${_p9k__n:=${${(M)${:-x$_p9k__bg}:#x(000|000)}:+14}}${_p9k__n:=15}${_p9k__v::=}${_p9k__c::="${P9K_CONTENT}"}${_p9k__c::=${_p9k__c//\C-M}}${_p9k__e::=${${_p9k__1rbackground_jobs+00}:-${${(%):-$_p9k__c%1(l.1.0)}[-1]}1}}}+}${${_p9k__e:#00}:+${_p9k_t[$_p9k__n]/<_p9k__w>/$_p9k__w}${_p9k__c}%b%K{000\\}%F{006\\}${${(M)_p9k__e:#11}:+ }$_p9k__v${${:-${_p9k__w::=%b%K{000\\}%F{006\\} %b%K{000\\}%F{006\\}}${_p9k__sss::=%b%K{000\\}%F{006\\} %k%F{000\\}%b%K{000\\}%F{006\\}}${_p9k__i::=3}${_p9k__bg::=000}}+}}}${${:-"${${:-$_p9k__keymap.$_p9k__zle_state}:#(vicmd.*|vivis.*|vivli.*|*.*insert*)}"}:+${${:-${P9K_CONTENT::=OVERTYPE}${_p9k__n::=}${${${_p9k__bg:-0}:#NONE}:-${_p9k__n::=28}}${_p9k__n:=${${(M)${:-x$_p9k__bg}:#x(003|003)}:+30}}${_p9k__n:=31}${_p9k__c::="${P9K_CONTENT}"}${_p9k__c::=${_p9k__c//\C-M}}${_p9k__e::=${${_p9k__1rvi_mode+00}:-${${(%):-$_p9k__c%1(l.1.0)}[-1]}0}}}+}${${_p9k__e:#00}:+${_p9k_t[$_p9k__n]/<_p9k__w>/$_p9k__w}${_p9k__c}%b%K{003\\}%F{000\\}${${:-${_p9k__w::=%b%K{003\\}%F{000\\} %b%K{003\\}%F{000\\}}${_p9k__sss::=%b%K{003\\}%F{000\\} %k%F{003\\}%b%K{003\\}%F{000\\}}${_p9k__i::=41}${_p9k__bg::=003}}+}}}${${:-"${(M)${:-$_p9k__keymap$_p9k__region_active}:#vicmd0}"}:+${${:-${P9K_CONTENT::=NORMAL}${_p9k__n::=}${${${_p9k__bg:-0}:#NONE}:-${_p9k__n::=32}}${_p9k__n:=${${(M)${:-x$_p9k__bg}:#x(002|002)}:+34}}${_p9k__n:=35}${_p9k__c::="${P9K_CONTENT}"}${_p9k__c::=${_p9k__c//\C-M}}${_p9k__e::=${${_p9k__1rvi_mode+00}:-${${(%):-$_p9k__c%1(l.1.0)}[-1]}0}}}+}${${_p9k__e:#00}:+${_p9k_t[$_p9k__n]/<_p9k__w>/$_p9k__w}${_p9k__c}%b%K{002\\}%F{000\\}${${:-${_p9k__w::=%b%K{002\\}%F{000\\} %b%K{002\\}%F{000\\}}${_p9k__sss::=%b%K{002\\}%F{000\\} %k%F{002\\}%b%K{002\\}%F{000\\}}${_p9k__i::=41}${_p9k__bg::=002}}+}}}${${:-"${(M)${:-$_p9k__keymap$_p9k__region_active}:#(vicmd1|vivis?|vivli?)}"}:+${${:-${P9K_CONTENT::=VISUAL}${_p9k__n::=}${${${_p9k__bg:-0}:#NONE}:-${_p9k__n::=36}}${_p9k__n:=${${(M)${:-x$_p9k__bg}:#x(004|004)}:+38}}${_p9k__n:=39}${_p9k__c::="${P9K_CONTENT}"}${_p9k__c::=${_p9k__c//\C-M}}${_p9k__e::=${${_p9k__1rvi_mode+00}:-${${(%):-$_p9k__c%1(l.1.0)}[-1]}0}}}+}${${_p9k__e:#00}:+${_p9k_t[$_p9k__n]/<_p9k__w>/$_p9k__w}${_p9k__c}%b%K{004\\}%F{000\\}${${:-${_p9k__w::=%b%K{004\\}%F{000\\} %b%K{004\\}%F{000\\}}${_p9k__sss::=%b%K{004\\}%F{000\\} %k%F{004\\}%b%K{004\\}%F{000\\}}${_p9k__i::=41}${_p9k__bg::=004}}+}}}${${:-${P9K_CONTENT::=08:53:09 AM}${_p9k__n::=}${${${_p9k__bg:-0}:#NONE}:-${_p9k__n::=40}}${_p9k__n:=${${(M)${:-x$_p9k__bg}:#x(007|007)}:+42}}${_p9k__n:=43}${_p9k__v::=}${_p9k__c::="${P9K_CONTENT}"}${_p9k__c::=${_p9k__c//\C-M}}${_p9k__e::=${${_p9k__1rtime+00}:-${${(%):-$_p9k__c%1(l.1.0)}[-1]}1}}}+}${${_p9k__e:#00}:+${_p9k_t[$_p9k__n]/<_p9k__w>/$_p9k__w}at ${_p9k__c}%b%K{007\\}%F{000\\}${${(M)_p9k__e:#11}:+ }$_p9k__v${${:-${_p9k__w::=%b%K{007\\}%F{000\\} %b%K{007\\}%F{000\\}}${_p9k__sss::=%b%K{007\\}%F{000\\} %k%F{007\\}%b%K{007\\}%F{000\\}}${_p9k__i::=46}${_p9k__bg::=007}}+}}$_p9k__sss%b%k%f}}${_p9k__lprompt::=${_p9k__1l_frame-"%240F╭─"}${_p9k__1l-${${:-${_p9k__bg::=NONE}${_p9k__i::=0}${_p9k__sss::=%f}}+}${${:-${P9K_CONTENT::=}${_p9k__n::=}${${${_p9k__bg:-0}:#NONE}:-${_p9k__n::=44}}${_p9k__n:=${${(M)${:-x007}:#x($_p9k__bg|${_p9k__bg:-0})}:+46}}${_p9k__n:=47}${_p9k__c::="${P9K_CONTENT}"}${_p9k__c::=${_p9k__c//\C-M}}${_p9k__e::=${${_p9k__1los_icon+00}:-${${(%):-$_p9k__c%1(l.1.0)}[-1]}0}}}+}${${_p9k__e:#00}:+${${_p9k_t[$_p9k__n]/<_p9k__ss>/$_p9k__ss}/<_p9k__s>/$_p9k__s}${_p9k__c}%b%K{007\\}%F{232\\} ${${:-${_p9k__s::=%F{007\\}}${_p9k__ss::=}${_p9k__sss::=%F{007\\}}${_p9k__i::=1}${_p9k__bg::=007}}+}}${(e)_p9k__vcs}%b%k$_p9k__sss%b%k%f}}}+}${(e)_p9k_t[6]}${_p9k__lprompt}${${_p9k__g+\n}:-${:-"%F{240}"}${${${_p9k__m:#-*}:+${${_p9k__1g+${(pl.$((_p9k__m+1)).. .)}}:-${(pl.$((_p9k__m+1))..─.)}}$_p9k__rprompt${_p9k_t[$((1+!_p9k__ind))]}}:-\n}%b%k%f}}${_p9k__2-${_p9k__2l_frame-"%240F╰─"}${_p9k__2l-${${:-${_p9k__bg::=NONE}${_p9k__i::=0}${_p9k__sss::=%f}}+}%b%k$_p9k__sss%b%k%f${:-" %b%k%f"}}}${${COLUMNS::=$_p9k__clm}+}'
_p9k_do_nothing () {
true
}
_zsh_autosuggest_start () {
if (( ${+ZSH_AUTOSUGGEST_MANUAL_REBIND} ))
then
add-zsh-hook -d precmd _zsh_autosuggest_start
fi
_zsh_autosuggest_bind_widgets
}
omz_termsupport_precmd () {
[[ "${DISABLE_AUTO_TITLE:-}" != true ]] || return
title "$ZSH_THEME_TERM_TAB_TITLE_IDLE" "$ZSH_THEME_TERM_TITLE_IDLE"
}
omz_termsupport_cwd () {
local URL_HOST URL_PATH
URL_HOST="$(omz_urlencode -P $HOST)" || return 1
URL_PATH="$(omz_urlencode -P $PWD)" || return 1
[[ -z "$KONSOLE_VERSION" ]] || URL_HOST=""
printf "\e]7;file://%s%s\e\\" "${URL_HOST}" "${URL_PATH}"
}
_p9k_precmd () {
__p9k_new_status=$?
__p9k_new_pipestatus=($pipestatus)
trap ":" INT
[[ -o ksh_arrays ]] && __p9k_ksh_arrays=1 || __p9k_ksh_arrays=0
[[ -o sh_glob ]] && __p9k_sh_glob=1 || __p9k_sh_glob=0
_p9k_restore_special_params
_p9k_precmd_impl
[[ ${+__p9k_instant_prompt_active} == 0 || -o no_prompt_cr ]] || __p9k_instant_prompt_active=2
setopt no_local_options no_prompt_bang prompt_percent prompt_subst prompt_cr prompt_sp
typeset -g __p9k_trapint='_p9k_trapint; return 130'
trap "$__p9k_trapint" INT
: ${(%):-%b%k%s%u}
}
_p9k_preexec1 () {
_p9k_restore_special_params
unset __p9k_trapint
trap - INT
}
omz_termsupport_preexec () {
[[ "${DISABLE_AUTO_TITLE:-}" != true ]] || return
emulate -L zsh
setopt extended_glob
local -a cmdargs
cmdargs=("${(z)2}")
if [[ "${cmdargs[1]}" = fg ]]
then
local job_id jobspec="${cmdargs[2]#%}"
case "$jobspec" in
(<->) job_id=${jobspec} ;;
("" | % | +) job_id=${(k)jobstates[(r)*:+:*]} ;;
(-) job_id=${(k)jobstates[(r)*:-:*]} ;;
([?]*) job_id=${(k)jobtexts[(r)*${(Q)jobspec}*]} ;;
(*) job_id=${(k)jobtexts[(r)${(Q)jobspec}*]} ;;
esac
if [[ -n "${jobtexts[$job_id]}" ]]
then
1="${jobtexts[$job_id]}"
2="${jobtexts[$job_id]}"
fi
fi
local CMD="${1[(wr)^(*=*|sudo|ssh|mosh|rake|-*)]:gs/%/%%}"
local LINE="${2:gs/%/%%}"
title "$CMD" "%100>...>${LINE}%<<"
}
_p9k_preexec2 () {
typeset -g _p9k__preexec_cmd=$2
_p9k__timer_start=EPOCHREALTIME
P9K_TTY=old
(( ! $+_p9k__iterm_cmd )) || _p9k_iterm2_preexec
}
|
It turns out source $ZSH/oh-my-zsh.sh in the ~/.zshrc was causing some issues with Powerlevel10k. Commented this line out and the prompt went back to normal after quitting iTerm2 and opening it back up.
| Double zsh prompt is showing unformatted then formatted |
1,485,634,653,000 |
I am unable to ssh to a server that asks for a diffie-hellman-group1-sha1 key exchange method:
ssh 123.123.123.123
Unable to negotiate with 123.123.123.123 port 22: no matching key exchange method found. Their offer: diffie-hellman-group1-sha1
How to enable the diffie-hellman-group1-sha1 key exchange method on Debian 8.0?
I have tried (as proposed here) to
add the following lines to my /etc/ssh/ssh_config
KexAlgorithms diffie-hellman-group1-sha1,[email protected],ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha1
Ciphers 3des-cbc,blowfish-cbc,aes128-cbc,aes128-ctr,aes256-ctr
regenerate keys with
ssh-keygen -A
restart ssh with
service ssh restart
but still get the error.
|
The OpenSSH website has a page dedicated to legacy issues such as this one. It suggests the following approach, on the client:
ssh -oKexAlgorithms=+diffie-hellman-group1-sha1 123.123.123.123
or more permanently, adding
Host 123.123.123.123
KexAlgorithms +diffie-hellman-group1-sha1
to ~/.ssh/config.
This will enable the old algorithms on the client, allowing it to connect to the server.
| How to enable diffie-hellman-group1-sha1 key exchange on Debian 8.0? |
1,485,634,653,000 |
I have two servers. Both servers are in CentOS 5.6. I want to SSH from Server 1 to Server 2 using a private key I have (OpenSSH SSH-2 Private Key).
I don't know how to do it over unix. But what I did on windows using Putty was to feed my OpenSSH private key to putty-gen and generate a private key in PPK format.
However, I would be creating a bash script from server 1 that will execute some commands on server 2 via SSH.
How do I SSH to Server 2 using my private key file from Server 1?
|
TL;DR: To use an existing private key inline you need to select the identity file path with the parameter -i as follows:
ssh -i '/path/to/keyfile' username@server
You need your SSH public key and you will need your ssh private key. Keys can be generated with ssh-keygen.
The private key must be kept on Server 1 and the public key must be stored on Server 2.
This is completly described in the manpage of openssh, so I will quote a lot of it. You should read the section 'Authentication'. Also the openSSH manual should be really helpful: http://www.openssh.org/manual.html
Please be careful with ssh because this affects the security of your server.
From man ssh:
~/.ssh/identity
~/.ssh/id_dsa
~/.ssh/id_rsa
Contains the private key for authentication. These files contain
sensitive data and should be readable by the user but not acces-
sible by others (read/write/execute). ssh will simply ignore a
private key file if it is accessible by others. It is possible
to specify a passphrase when generating the key which will be
used to encrypt the sensitive part of this file using 3DES.
~/.ssh/identity.pub
~/.ssh/id_dsa.pub
~/.ssh/id_rsa.pub
Contains the public key for authentication. These files are not
sensitive and can (but need not) be readable by anyone.
This means you can store your private key in your home directory in .ssh. Another possibility is to tell ssh via the -i parameter switch to use a special identity file.
Also from man ssh:
-i identity_file
Selects a file from which the identity (private key) for RSA or
DSA authentication is read. The default is ~/.ssh/identity for
protocol version 1, and ~/.ssh/id_rsa and ~/.ssh/id_dsa for pro-
tocol version 2. Identity files may also be specified on a per-
host basis in the configuration file. It is possible to have
multiple -i options (and multiple identities specified in config-
uration files).
This is for the private key. Now you need to introduce your public key on Server 2. Again a quote from man ssh:
~/.ssh/authorized_keys
Lists the public keys (RSA/DSA) that can be used for logging in
as this user. The format of this file is described in the
sshd(8) manual page. This file is not highly sensitive, but the
recommended permissions are read/write for the user, and not
accessible by others.
The easiest way to achive that is to copy the file to Server 2 and append it to the authorized_keys file:
scp -p your_pub_key.pub user@host:
ssh user@host
host$ cat id_dsa.pub >> ~/.ssh/authorized_keys
Authorisation via public key must be allowed for the ssh daemon, see man ssh_config. Usually this can be done by adding the following statement to the config file:
PubkeyAuthentication yes
| How to ssh to remote server using a private key? |
1,485,634,653,000 |
I've read the official definition:
ssh-agent is a program to hold private keys used for public key authentication (RSA, DSA, ECDSA). The idea is that ssh-agent is started in the beginning of an X-session or a login session, and all other windows or programs are started as clients to the ssh-agent program. Through use of environment variables the agent can be located and automatically used for authentication when logging in to other machines using ssh(1).
"a program to hold private keys" - IMHO, ssh keys are generated by a user with the ssh-keygen command and simply stored in ~/.ssh - why do I need some daemon to hold these keys? How exactly does it hold them anyways? - aren't they just stored in .ssh?
"are started as clients to the ssh-agent program" - I don't get it. Where would one need that? I usually just use ssh as this:
ssh -i ~/.ssh/private_key_name username@hostname
What exactly does the above definition mean by "clients"? What clients? Don't you just run the ssh command from a terminal to connect to another machine? What other clients are there and why can't they just use the standard path to that private key file, just like the ssh command?
|
The SSH agent handles signing of authentication data for you. When authenticating to a server, you are required to sign some data using your private key, to prove that you are, well, you.
As a security measure, most people sensibly protect their private keys with a passphrase, so any authentication attempt would require you to enter this passphrase. This can be undesirable, so the ssh-agent caches the key for you and you only need to enter the password once, when the agent wants to decrypt it (and often not even that, as the ssh-agent can be integrated with pam, which many distros do).
The SSH agent never hands these keys to client programs, but merely presents a socket over which clients can send it data and over which it responds with signed data. A side benefit of this is that you can use your private key even with programs you don't fully trust.
Another benefit of the SSH agent is that it can be forwarded over SSH. So when you ssh to host A, while forwarding your agent, you can then ssh from A to another host B without needing your key present (not even in encrypted form) on host A.
| what's the purpose of ssh-agent? |
1,485,634,653,000 |
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.
|
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
| What's the purpose of the randomart image for user (not host) SSH keys? |
1,485,634,653,000 |
I know what it does, but I don't know why. What attack(s) does it prevent?
Is it relevant for all kind of authentication methods? (hostbased, password, publickey, keyboard-interactive ...)
|
The UseDNS option is mostly useless. If the client machines are out there on the Internet, there is a high chance that they don't have any reverse DNS, their reverse DNS doesn't resolve forward, or their DNS doesn't provide any information other than “belongs to this ISP” which the IP address already tells you.
In typical configurations, DNS is only used for logging. It can be used for authentication, but only if IgnoreRhosts no is specified in sshd_config. This is for compatibility with old installations that used rsh, where you can say “the user called bob on the machine called darkstar may log in as alice without showing any credentials” (by writing darkstar bob in ~alice/.rhosts). It is only secure if you trust all the machines that may possibly be connecting to the ssh server. In other words, this is very very rarely usable in a secure way.
Given that the DNS lookup doesn't provide any useful information except in very peculiar circumstances, it should be turned off. As far as I can tell, the only reason it's on by default is that it's technically more secure (if you're concerned about authentication, not availability), even though that only applies to a tiny set of circumstances.
Another argument for turning off this feature is that every superfluous feature is an unnecessary security risk.
| What is the point of sshd “UseDNS” option? |
1,485,634,653,000 |
I can't find my sshd logs in the standard places.
What I've tried:
Not in /var/log/auth.log
Not in /var/log/secure
Did a system search for 'auth.log' and found nothing
I've set /etc/ssh/sshd_config to explicitly use SyslogFacility AUTH and LogLevel INFO and restarted sshd and still can't find them.
I'm using OpenSSH 6.5p1-2 on Arch Linux.
|
I have found the output of sshd and other core services in 'journalctl'.
See more at the Arch Wiki entry for systemd:
https://wiki.archlinux.org/index.php/Systemd/Journal
| Where are my sshd logs? |
1,485,634,653,000 |
Is there a way to structure a single command to login via SSH to a remote server and run a program on the remote login shell?
In the OpenSSH manual, it reads "If command is specified, it is executed on the remote host instead of a login shell." So, for example, ssh user@server mail will login to the remote server, display the mailbox status, and then return you to the local shell. Is there a way to stay on the remote shell after displaying the mail status?
Furthermore, ssh user@server [command] does not seem to work if the command is a program, for example vim or mutt. Is there a way to login to the remote shell and run a program while staying in the remote shell during the program and after exiting the program, only finally exiting upon a specific logout command (just like in a normal SSH session)?
I would eventually like to be able to put such a command as an alias in the local .bashrc, so that it could be run quickly when desired. An example would be to login via SSH to a remote server and open mutt on the remote server to read or send email.
|
Have you tried ssh -t user@server "mail && bash" (or replace bash with whatever shell you like)?
The -t is necessary in order to create a pseudo-tty for bash to use as an interactive shell.
| Single command to login to SSH and run program? |
1,485,634,653,000 |
I'm using a Match block in OpenSSH's /etc/ssh/sshd_config (on debian) to restrict some users to SFTP:
# my stuff
Match group sftponly
X11Forwarding no
AllowTcpForwarding no
ForceCommand internal-sftp -u 0002
ChrootDirectory %h
As you can see, I use a #my stuff comment in custom config files to easily distinguish default configurations from those I made (and I put those at the end of the config files).
Now I wanted to append the directive UseDNS no to the configuration (to speed up logins) but OpenSSH said Directive 'UseDNS' is not allowed within a Match block.
Now I was wondering whether there is a syntax like End Match to end those match blocks?
|
To end up a match block with openssh 6.5p1 or above, use the line: Match all
Here is a piece of code, taken from my /etc/ssh/sshd_config file:
# Change to no to disable tunnelled clear text passwords
PasswordAuthentication no
Match host 192.168.1.12
PasswordAuthentication yes
Match all
X11Forwarding yes
X11DisplayOffset 10
A line with a sole Match won't work. (It didn't work for me, sshd refused to start)
| OpenSSH: How to end a match block |
1,485,634,653,000 |
I know how to connect 'to' a certain port using ssh.
ssh user@remotehostip -p XXX
Is there a way to establish ssh from the port which my local computer will be using?
|
That is not easily possible. How that can be done depends on where the source port shall be seen: Locally, too, or is it enough if it's the right port from the perspective of the external network?
You can run the SSH client in an LXC container. I have never done that thus I cannot explain it to you in detail. But you create a virtual network interface and attach it to this container so that ssh uses this interface because it is the only (external) interface it sees.
On the host system it should be possible to detect that a packet comes from this interface. Thus you can use Netfilter's NAT (SNAT) for rewriting the source address with something like:
iptables -t nat -A POSTROUTING -o vnet0 -p tcp --dport 22 -j SNAT --to-source :1234
Of course, this does not work (or becomes more complicated) if you connect to ports different from 22.
| How to connect ssh from a specified port? |
1,485,634,653,000 |
I've found that ssh-keygen ("ssh" package) produces different keys from puttygen ("putty" package).
If I create public and private keys with ssh-keygen some SSH servers will not accept my keys. If I create keys with puttygen only one server does accept it.
Why don't Linux repositories propose some common solution (package) for it?
I've found another package ssh-3.2.9.1 which creates keys that work with PuTTY. But why isn't there any handy solution in SSH?
|
OpenSSH is the de facto standard implementation of the SSH protocol. If PuTTY and OpenSSH differ, PuTTY is the one that's incompatible.
If you generate a key with OpenSSH using ssh-keygen with the default options, it will work with virtually every server out there. A server that doesn't accept such a key would be antique, using a different implementation of SSH, or configured in a weird restrictive way. Keys of a non-default type may not be supported on some servers. In particular, ECDSA keys make session establishment very slightly faster, but they are only supported by recent versions of OpenSSH.
PuTTY uses a different key file format. It comes with tools to convert between its own .ppk format and the format of OpenSSH.
This ssh-3.2.9.1 you found is a commercial product which has its own different private key format. There isn't any reason to use it instead of OpenSSH. It can only be less compatible, it requires paying, and there's about zero tutorials on how to use it out there.
| What is the difference between an OpenSSH key and PuTTY key? |
1,485,634,653,000 |
I am trying to ssh to remote machine, the attempt fails:
$ ssh -vvv [email protected]
OpenSSH_7.7p1, OpenSSL 1.0.2o 27 Mar 2018
.....
debug2: ciphers ctos: aes128-cbc,3des-cbc,aes192-cbc,aes256-cbc
debug2: ciphers stoc: aes128-cbc,3des-cbc,aes192-cbc,aes256-cbc
debug2: MACs ctos: [email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: [email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,[email protected]
debug2: compression stoc: none,[email protected]
debug2: languages ctos:
debug2: languages stoc:
debug2: first_kex_follows 0
debug2: reserved 0
debug1: kex: algorithm: curve25519-sha256
debug1: kex: host key algorithm: rsa-sha2-512
Unable to negotiate with 192.168.100.14 port 22: no matching cipher found. Their offer: aes128-cbc,3des-cbc,aes192-cbc,aes256-cbc
As far as I understand the last string of the log, the server offers to use one of the following 4 cipher algorithms: aes128-cbc,3des-cbc,aes192-cbc,aes256-cbc. Looks like my ssh client doesn't support any of them, so the server and client are unable to negotiate further.
But my client does support all the suggested algorithms:
$ ssh -Q cipher
3des-cbc
aes128-cbc
aes192-cbc
aes256-cbc
[email protected]
aes128-ctr
... and there are several more.
And if I explicitly specify the algorithm like this:
ssh -vvv -c aes256-cbc [email protected]
I can successfully login to the server.
My ~/.ssh/config doesn't contain any cipher-related directives (actually I removed it completely, but the problem remains).
So, why client and server can't decide which cipher to use without my explicit instructions? The client understands that server supports aes256-cbc, client understands that he can use it himself, why not just use it?
Some additional notes:
There was no such problem some time (about a month) ago. I've not changed any ssh configuration files since then. I did update installed packages though.
There is a question which describes very similar-looking problem, but there is no answer my question: ssh unable to negotiate - no matching key exchange method found
UPDATE: problem solved
As telcoM explained the problem is with server: it suggests only the obsolete cipher algorithms. I was sure that both client and server are not outdated. I have logged into server (by the way, it's Synology, updated to latest available version), and examined the /etc/ssh/sshd_config. The very first (!) line of this file was:
Ciphers aes128-cbc,3des-cbc,aes192-cbc,aes256-cbc
This is very strange (the fact that line is very first in the file), I am sure I've never touched the file before. However I've changed the line to:
Ciphers aes256-ctr,aes128-cbc,3des-cbc,aes192-cbc,aes256-cbc
restarted the server (did not figure out how to restart the sshd service only), and now the problem is gone: I can ssh to server as usual.
|
The -cbc algorithms have turned out to be vulnerable to an attack. As a result, up-to-date versions of OpenSSH will now reject those algorithms by default: for now, they are still available if you need them, but as you discovered, you must explicitly enable them.
Initially when the vulnerability was discovered (in late 2008, nearly 10 years ago!) those algorithms were only placed at the tail end of the priority list for the sake of compatibility, but now their deprecation in SSH has reached a phase where those algorithms are disabled by default. According to this question in Cryptography.SE, this deprecation step was already happening in year 2014.
Please consider this a gentle reminder to update your SSH server, if at all possible. (If it's a firmware-based implementation, see if updated firmware is available for your hardware.)
| ssh Unable to negotiate: "no matching cipher found", is rejecting cbc |
1,485,634,653,000 |
The OpenSSH daemon has many "default" values for its settings. So looking at the sshd_config might not give someone the complete set of active settings.
How to display the full sshd configuration (for OpenSSH)?
|
The OpenSSH sshd command has an extended test switch which can be used to "Check the validity of the configuration file, output the effective configuration to stdout and then exit." (source sshd man page).
So the answer is (as root, or prefixing it with sudo):
sshd -T
(the settings are not in alphabetical order, one can use sshd -T | sort to quickly look for one setting, or just grep the setting) :-)
PS: my first reflex was looking for this answer online, but the search engines were not helpful. And then only looked at the man page and found the answers. For those lazy like me which turns too quickly to the internet, there is now the answer posted online! Lesson learned today: check the man page first, ask a search engine later if needed.
| Display full settings of sshd |
1,485,634,653,000 |
I have built a new Ubuntu server in AWS. Now for some reason my private key that works on other Ubuntu servers is not working her . The error in auth.log is
userauth_pubkey: key type ssh-rsa not in PubkeyAcceptedAlgorithms [preauth]
This only is an issue with Putty, if I try logging via a linux workstation no issues at all with any machine.
The difference I see is the new server is
Ubuntu 22.04.1 LTS running OpenSSH_8.9p1 Ubuntu-3, OpenSSL 3.0.2 15 Mar 2022
The working (old) server is
Ubuntu 20.04.4 LTS (Focal Fossa) running OpenSSH_8.2p1 Ubuntu-4ubuntu0.4, OpenSSL 1.1.1f 31 Mar 2020
Has something changed in this version of OpenSSH? How do I get putty working again?
|
A simple solution.
Add this line in /etc/ssh/sshd_config.
PubkeyAcceptedAlgorithms +ssh-rsa
Afterwards, restart the sshd service to make the new settings come into effect.
$ sudo systemctl restart sshd
| SSH server gives "userauth_pubkey: key type ssh-rsa not in PubkeyAcceptedAlgorithms [preauth]" when connecting with Putty |
1,485,634,653,000 |
My understanding of the way ~/.ssh/config works is that each 'Host ' line takes effect for any host matching after that point in the config file.
I have a number of personal servers and work servers that I need to connect to. I'm trying to do something like the following:
# General Settings
ControlMaster auto
ControlPath ~/.ssh/controlmaster/%r@%h:%p
ForwardAgent yes
ForwardX11 yes
GSSAPIAuthentication no
PubkeyAuthentication yes
# Personal Servers
Host *
User harleypig
IdentityFile ~/.ssh/personal_id_rsa
Host host1
Hostname host1.com
Host host2
Hostname host2.com
# Work Servers
Host *
User alan.young
IdentityFile ~/.ssh/work_id_rsa
Host work1
Hostname work1.companyserver.com
Host work2
Hostname work2.companyserver.com
Host *
User devuser
Host dev1
Hostname dev1.companyserver.com
Host dev2
Hostname dev2.companyserver.com
The docs seem to indicate that host1 and host2 should use 'personal_id_rsa' and the user harleypig. work1, work2, dev1 and dev2 should use 'work_id_rsa' and the first two should be the user 'alan.young' and dev1 and dev2 should be the user 'devuser'
However, this is not happening. Whatever 'Host *' I put first is what all of the following hosts try to connect with. Am I misunderstanding or missing something?
|
From the ssh_config manual:
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.
So in your example, all hosts will use User harleypig and IdentityFile ~/.ssh/personal_id_rsa.
Think of Host directives with wildcards as fallbacks: use the following settings only if they haven't been set yet. You need to write something like this:
Host host1
Hostname host1.com
Host host2
Hostname host2.com
Host host*
User harleypig
IdentityFile ~/.ssh/personal_id_rsa
You can put multiple patterns on a Host line if a given set of host aliases can't be matched with wildcards, e.g. Host host* more* outlier.
| Multiple 'Host *' in ssh_config? |
1,485,634,653,000 |
So ssh has the option HostKeyAlgorithms. Sample usage:
ssh -o "HostKeyAlgorithms ssh-rsa" user@hostname
I'm trying to get the client to connect using the servers ecdsa key, but I can't find what the correct string is for that.
What command can I use to get a list of the available HostKeyAlgorithms?
|
ssh -Q key
Unless you have an ancient version of OpenSSH, in which case uhhhh source dive, or run ssh -v -v -v ... and see if what you want appears there.
| How do I list available host key algorithms for an SSH client? |
1,485,634,653,000 |
Today, after doing updates in Debian Stretch, it started displaying these warnings when restarting the ssh service with my current config:
/etc/ssh/sshd_config line 17: Deprecated option KeyRegenerationInterval
/etc/ssh/sshd_config line 18: Deprecated option ServerKeyBits
/etc/ssh/sshd_config line 29: Deprecated option RSAAuthentication
/etc/ssh/sshd_config line 36: Deprecated option RhostsRSAAuthentication
[....] Restarting OpenBSD Secure Shell server: sshd
/etc/ssh/sshd_config line 17: Deprecated option KeyRegenerationInterval
/etc/ssh/sshd_config line 18: Deprecated option ServerKeyBits
/etc/ssh/sshd_config line 29: Deprecated option RSAAuthentication
/etc/ssh/sshd_config line 36: Deprecated option RhostsRSAAuthentication
What is happening here?
Using Debian 9 with OpenSSH 7.4
|
In the current Stretch update, openssh version changed from 7.3 to 7.4, released on 2016-Dec-19.
As it can be inferred from the Release notes, and from @Jakuje comments, OpenSSH maintainers have removed the corresponding configuration options for good, as they are obsolete.
So the lines can be safely removed.
Also, take head of:
Future deprecation notice
We plan on retiring more legacy cryptography in future releases,
specifically:
In approximately August 2017, removing remaining support for the
SSH v.1 protocol (client-only and currently compile-time disabled).
In the same release, removing support for Blowfish and RC4 ciphers
and the RIPE-MD160 HMAC. (These are currently run-time disabled).
Refusing all RSA keys smaller than 1024 bits (the current minimum
is 768 bits)
The next release of OpenSSH will remove support for running sshd(8)
with privilege separation disabled.
The next release of portable OpenSSH will remove support for
OpenSSL version prior to 1.0.1.
| Deprecated options when restarting openssh in Stretch |
1,485,634,653,000 |
I have the following entry in my .ssh/config file
Host AAA
User BBB
HostName CCC
ControlMaster auto
ControlPath ~/.ssh/%r@%h:%p
The above allows me to multiplex multiple ssh sessions through the same ssh connection without having to type in the password every time I need a new session (as long as the master connection remains open).
However, I have noticed that once I have a relatively high # of connections multiplexed (~7), I can't add more sessions to the same multiplexed connection, and I start get the following error:
> ssh -X AAA
mux_client_request_session: session request failed: Session open refused by peer
Password:
My questions:
Why am I getting this error? Is there a limit in the # of ssh sessions I can multiplex in the same connection? Can I change that limit? Would that be a bad idea?
|
The sshd daemon on the server is limiting the number of sessions per network connection. This is controlled by MaxSessions option in /etc/ssh/sshd_config. Also the MaxStartups option may need to be increased if you use a large number of sessions. (See man sshd_config for more details.) The option to modify MaxSessions limit has been introduced in OpenSSH 5.1 and it looks that the number was previously hard-fixed at 10. If you exceed MaxSessions on the server, you'll see sshd[####]: error: no more sessions in the server's log.
| Limits of SSH multiplexing |
1,485,634,653,000 |
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 identical
In 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?
|
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.pub
Convert 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.pub
The 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_e
Looking 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-openssh
The 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
AAAAB3NzaC1yc2EAAAADAQABAAABAQDFkZdpmbze9c6pT883rE1i64TJd4wb
Comparison 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
| Convert OpenSSH private key into SSH2 private key |
1,485,634,653,000 |
I read about setting up ssh keys in Linux and have some questions. Correct me if I'm wrong…
Let's say host tr-lgto wants to connect to host tr-mdm using ssh. If we want to be sure that it's the real tr-mdm, we generate a pair of keys on tr-mdm and we add the public key to known_hosts on tr-lgto.
If tr-mdm wants to check that it's the real tr-lgto, then tr-lgto has to generate a keypair and add the public key to authorized_keys on tr-mdm.
Question 1: There is no user field in file known_hosts, just IP addresses and hostnames. tr-mdm might have a lot of users, each with their own .ssh folder. Should we add the public key to each of the known_hosts files?
Question 2: I found that ssh-keyscan -t rsa tr-mdm will return the public key of tr-mdm. How do I know what user this key belongs to? Moreover, the public key in /root/.ssh/ is different from what that command returns. How can this be?
|
You're mixing up the authentication of the server machine to the client machine, and the authentication of the user to the server machine.
Server authentication
One of the first things that happens when the SSH connection is being established is that the server sends its public key to the client, and proves (thanks to public-key cryptography) to the client that it knows the associated private key. This authenticates the server: if this part of the protocol is successful, the client knows that the server is who it pretends it is.
The client may check that the server is a known one, and not some rogue server trying to pass off as the right one. SSH provides only a simple mechanism to verify the server's legitimacy: it remembers servers you've already connected to, in the ~/.ssh/known_hosts file on the client machine (there's also a system-wide file /etc/ssh/known_hosts). The first time you connect to a server, you need to check by some other means that the public key presented by the server is really the public key of the server you wanted to connect to. If you have the public key of the server you're about to connect to, you can add it to ~/.ssh/known_hosts on the client manually.
Authenticating the server has to be done before you send any confidential data to it. In particular, if the user authentication involves a password, the password must not be sent to an unauthenticated server.
User authentication
The server only lets a remote user log in if that user can prove that they have the right to access that account. Depending on the server's configuration and the user's choice, the user may present one of several forms of credentials (the list below is not exhaustive).
The user may present the password for the account that he is trying to log into; the server then verifies that the password is correct.
The user may present a public key and prove that he possesses the private key associated with that public key. This is exactly the same method that is used to authenticate the server, but now the user is trying to prove their identity and the server is verifying them. The login attempt is accepted if the user proves that he knows the private key and the public key is in the account's authorization list (~/.ssh/authorized_keys on the server).
Another type of method involves delegating part of the work of authenticating the user to the client machine. This happens in controlled environments such as enterprises, when many machines share the same accounts. The server authenticates the client machine by the same mechanism that is used the other way round, then relies on the client to authenticate the user.
| SSH key-based authentication: known_hosts vs authorized_keys |
1,485,634,653,000 |
I am using Open SSH (OpenSSH_6.6.1p1, OpenSSL 1.0.1i 6 Aug 2014) in Windows 8.1.
X11 Forwarding does not appear to be working. The DISPLAY environment variable does not appear to be set.
For example, if I use BitVise or Putty to connect, and run env, I see:
[marko@vm:~]$ env
XDG_SESSION_ID=6
TERM=xterm
SHELL=/bin/bash
SSH_CLIENT=192.168.1.174 61102 22
SSH_TTY=/dev/pts/0
USER=marko
MAIL=/var/mail/marko
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games
PWD=/home/marko
LANG=en_CA.UTF-8
NODE_PATH=/usr/lib/nodejs:/usr/lib/node_modules:/usr/share/javascript
SHLVL=1
HOME=/home/marko
LANGUAGE=en_CA:en
LOGNAME=marko
SSH_CONNECTION=192.168.1.174 61102 192.168.1.64 22
XDG_RUNTIME_DIR=/run/user/1000
DISPLAY=localhost:10.0
_=/usr/bin/env
If I instead use OpenSSH (ssh -X marko@vm):
[marko@vm:~]$ env
XDG_SESSION_ID=8
TERM=cygwin
SHELL=/bin/bash
SSH_CLIENT=192.168.1.174 61150 22
SSH_TTY=/dev/pts/1
USER=marko
MAIL=/var/mail/marko
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games
PWD=/home/marko
LANG=en_CA.UTF-8
NODE_PATH=/usr/lib/nodejs:/usr/lib/node_modules:/usr/share/javascript
SHLVL=1
HOME=/home/marko
LANGUAGE=en_CA:en
LOGNAME=marko
SSH_CONNECTION=192.168.1.174 61150 192.168.1.64 22
XDG_RUNTIME_DIR=/run/user/1000
_=/usr/bin/env
|
Have you set DISPLAY environment variable on the client? I'm not sure which shell you are using, but with Bourne shell derivative (like bash), please try:
export DISPLAY=127.0.0.1:0
ssh -X marko@vm
Or if you're using cmd.exe:
set DISPLAY=127.0.0.1:0
ssh -X marko@vm
Or if you're using powershell.exe:
$env:DISPLAY = '127.0.0.1:0'
ssh -X marko@vm
| -X flag (X11 Forwarding) does not appear to work in Windows |
1,485,634,653,000 |
The OpenSSH client has a command line option for port forwarding, used like this:
ssh -L localport:server:serverport user@host
which will connect to host as user, and at the same time redirecting localport on the client to serverport on server (which can be host or anything reachable from host over the network).
Now suppose I have SSHed into host doing just
ssh user@host
and in the middle of the session I realize I forgot to forward the port. Alas, I am in the middle of something, so I don’t just want to log out and re-establish the SSH connection with the port forwarding.
Is there a way to add port forwarding to a running SSH session?
|
From man 1 ssh:
ESCAPE CHARACTERS
When a pseudo-terminal has been requested, ssh supports a number of functions through the use of an escape character.
A single tilde character can be sent as ~~ or by following the tilde by a character other than those described below. The escape character must always follow a newline to be interpreted as special. The escape character can be changed in configuration files using the EscapeChar configuration directive or on the command line by the -e option.
The supported escapes (assuming the default ~) are:
[…]
~C
Open command line. Currently this allows the addition of port forwardings using the -L, -R and -D options (see above). […] Basic help is available, using the -h option.
So type Enter~C (i.e. capital c), then
-L localport:server:serverport
with desired localport, server and serverport, finally Enter.
Notes:
The initial Enter will be immediately sent to the remote side and may cause some action there, so pick a good moment (e.g. when you're in a shell with an empty command line). Or if you are sure the last thing you have typed is Enter anyway (e.g. you have just invoked a command that is now running), you can start directly with ~ because Enter has already been noticed by your local ssh.
On internationalized keyboards the tilde could be a dead key for generating special 'tilded' characters (like pressing ~n to generate ñ). In that case, it could be necessary to press SPACE after ~ to generate a single tilde, i.e: ENTER~SPACEC. In the case of the Spanish/LA keyboard layouts, as there is no combined character using tilde and C, the space can be omitted and the ~C generates the desired sequence.
Regarding multiple redirections, the ssh escaped command line only accepts a single command. You should press again the keyboard sequence to enter another command or redirection.
| Add port forwarding to a running SSH session |
1,485,634,653,000 |
One of my ec2 servers has stopped receiving ssh connections. The OS is Ubuntu server 8.04, and the ssh server is the standard openssh-server.
After months of uptime, I tried to connet to it today, and got the following message:
ssh_exchange_identification: Connection closed by remote host
Any idea what could have went wrong?
Update: After a reboot, the server started receiving new connections. Disks are below 50% usage.
|
Now that you once again have access, check the log to determine what, if any, clues there are as to why you were blocked.
tail -n300 /var/log/auth.log | grep ssh 1
The other thing to remember is that, if it happens again, you can run ssh in verbose mode with the -vvv option, which will return more detailed diagnostic information. From man ssh:
-v Verbose mode. Causes ssh to print debugging messages about its progress. This is helpful in debugging connection, authentication, and configuration problems. Multiple -v options increase the verbosity. The maximum is 3.
[1] You may need to increase/decrease the amount you tail by (-n) to identify the relevant entries.
| ssh server: reasons for sudden "Connection closed by remote host" |
1,485,634,653,000 |
I'm attempting to set up an SSH server on my local machine using OpenSSH.
When I try to SSH from a remote host into my local SSH server, the SSH server doesn't respond and the request times out. I'm pretty sure there's a really obvious fix for this that I'm simply overlooking.
Here's what happens when I try to SSH in from a remote host:
yoshimi@robots:/$ ssh -vv [email protected]
OpenSSH_6.7p1 Debian-5, OpenSSL 1.0.1k 8 Jan 2015
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug2: ssh_connect: needpriv 0
debug1: Connecting to 99.3.26.94 [99.3.26.94] port 22.
debug2: fd 3 setting O_NONBLOCK
debug1: connect to address 99.3.26.94 port 22: Connection timed out
ssh: connect to host 99.3.26.94 port 22: Connection timed out
Where robots is my remote host, and 99.3.26.94 is my local SSH server.
SSH Is Running
volt@arnold:~$ ps -A | grep sshd
5784 ? 00:00:00 sshd
Where arnold is my local SSH server.
Port Forwarding Is Set Up On the Router
I've got my home router set up to forward ports 80 and 22 to my SSH server. Interestingly, port 80 worked without a hitch -- goes straight to the Apache web directory. Port 22 -- not so much.
NMap Says It's Filtered
yoshimi@robots:/$ nmap -p 22 99.3.26.94
Starting Nmap 6.47 ( http://nmap.org ) at 2015-06-02 14:45 EDT
Nmap scan report for 99-3-26-94.lightspeed.bcvloh.sbcglobal.net (99.3.26.94)
Host is up (0.33s latency).
PORT STATE SERVICE
22/tcp filtered ssh
Nmap done: 1 IP address (1 host up) scanned in 7.59 seconds
Where robots is my remote host, and 99.3.26.94 is my local SSH server.
It's Not IPTables (I think)
volt@arnold:~$ sudo iptables -L
Chain INPUT (policy ACCEPT)
target prot opt source destination
fail2ban-ssh tcp -- anywhere anywhere multiport dports ssh
ACCEPT tcp -- anywhere anywhere tcp dpt:ssh
ACCEPT tcp -- anywhere anywhere tcp dpt:http
Chain FORWARD (policy ACCEPT)
target prot opt source destination
Chain OUTPUT (policy ACCEPT)
target prot opt source destination
Chain fail2ban-ssh (1 references)
target prot opt source destination
RETURN all -- anywhere anywhere
...And I don't have any other firewalls in place -- it's a relatively fresh Debian netinst.
So, then: What else could it be? It certainly appears to be a firewall-y sort of thing to just ignore traffic, but if it's not the router, it's not iptables, and it's not another firewall on the SSH server, ...what the heck else is there??
EDIT: Connection Request from Internal Network Error
yoshimi@robots:/$ ssh [email protected]
ssh: connect to host 192.168.1.90 port 22: No route to host
|
A Very Disappointing Self-Answer
Having set this problem aside for a day and come back to it, I was both relieved and perturbed (more perturbed than relieved) to find that everything was, mysteriously, working properly.
So, What Was the Issue?
No settings were changed or adjusted -- not on the router, not on the SSH server, and not on the SSH client's machine. It's fairly safe to say it was the router not handling the incoming traffic properly, in spite of proper settings. Given that dinky home router software isn't really designed to deal with port forwarding, it took the poor guy a while to implement the necessary changes.
But It's Been Like 6 Hours!!
Yeah dude, I know. I spent all day trying to figure out what was wrong -- and didn't ever find it because there wasn't anything wrong. Evidently, it can take 6 hours -- possibly more -- for the router settings to take effect.
So How Do I Know If This Is My Issue?
A nifty tool I came across during this escapade is tcpdump. This lean little guy sniffs traffic for you, offering valuable insight into what's actually going on. Plus, he's got some super filtering features that allow you to narrow down exactly what you want to look at/for. For example, the command:
tcpdump -i wlan1 port 22 -n -Q inout
Tells tcpdump to look for traffic via the wlan1 interface (-i = 'interface'), only through port 22, ignore DNS name resolution (-n = 'no name resolution'), and we want to see both incoming and outgoing traffic (-Q accepts in, out, or inout; inout is the default).
By running this command on your SSH server while attempting to connect via a remote machine, it quickly becomes clear where precisely the problem lies. There are, essentially, 3 possibilities:
If you're seeing incoming traffic from the remote machine, but no outgoing traffic from your local server, the problem lies with the server: there's probably a firewall rule that needs to be changed, etc.
If you're seeing both incoming and outgoing, but your remote machine isn't receiving the response, it's most likely the router: it's allowing the incoming traffic, but dropping your outgoing packets.
If there's no traffic at all, that's probably a router issue as well: the remote machine's SYN packets are being ignored and dropped by the router before they even reach your server.
And once you've discovered where the problem lies, a fix is (usually) trivial.
| SSH Server not answering connection requests |
1,485,634,653,000 |
I'm using openssh on both client and server. I know I can run ssh -L or ssh -R to setup some port redirections over ssh. However, since they are command-line parameters, such redirections must be written before the connection is opened.
Can I setup port redirections on-the-fly using the command-line ssh client?
When I used the PuTTY ssh client, I could interactively setup a port redirection while a connection was already opened, without dropping nor reconnecting, thus I know it is technically possible.
|
If you're using the SSH command line, and you haven't switched the escape character feature off, then you can type ~C after a newline to open a mini-console on the ssh client. Then type -L port:host:port or -R port:host:port or -D port as you would on the command line to add a redirection, or -KR port to remove a redirection.
A more flexible method to set up redirections without redoing the authentication is to start the first ssh client as a master (-M or -o ControlMaster=auto) and subsequent clients as slaves (-S or -o ControlMaster=auto). The slaves tunnel through the connection established by the master. You may need to set ControlPath on the command line or in your ~/.ssh/config; see the description of the options in the ssh_config man page for more information.
| How to setup port redirection after a ssh connection has been opened? |
1,485,634,653,000 |
So SSH has these files that configure settings for a specific user.
~/.ssh/authorized_keys
~/.ssh/config
~/.ssh/id_rsa
~/.ssh/id_rsa.pub
~/.ssh/known_hosts
I'd like to globalise some of these files, like config and known_hosts. So that other users ( including root ) could share the configured hosts.
What would be the best way to do this?
|
For ~/.ssh/config you can place relevant system-wide settings in /etc/ssh/ssh_config according to the man page:
ssh(1) obtains configuration data from the following sources in the following order:
command-line options
user's configuration file (~/.ssh/config)
system-wide configuration file (/etc/ssh/ssh_config)
For each parameter, the first obtained value will be used. The configuration files contain sections separated by “Host” specifications, and that section is only applied for hosts that match one of the patterns given in the specification.
Note that only the first value will be used, which means that the user can always override the system-wide configuration options locally.
For ~/.ssh/known_hosts you can use /etc/ssh/ssh_known_hosts or another file specified by the GlobalKnownHostsFile configuration option:
GlobalKnownHostsFile
Specifies a file to use for the global host key database instead of /etc/ssh/ssh_known_hosts.
I'm unsure if it is possible for the other files, but I imagine you could work something out with symlinks if you really wanted to share private keys among users as well.
| making ssh hosts global to all the users on the computer |
1,485,634,653,000 |
I'm using openssh7.5p1 and gnupg 2.1.21 on arch linux (these are the default versions that come with arch). I would like to use gpg-agent as an ssh agent. I put the following in my ~/.gnupg/gpg-agent.conf:
pinentry-program /usr/bin/pinentry-qt
enable-ssh-support
Arch automatically starts a gpg-agent from systemd, so I set
export SSH_AUTH_SOCK="$XDG_RUNTIME_DIR/gnupg/S.gpg-agent.ssh"
When I run ssh-add -l, it reports no identities and ps reports a gpg-agent --supervised process as I would expect.
Unfortunately, when I run ssh-add, no matter what the key type, it doesn't work. Here is an example of how I tried dsa:
$ ssh-keygen -f testkey -t dsa -N ''
Generating public/private dsa key pair.
Your identification has been saved in testkey.
Your public key has been saved in testkey.pub.
$ ssh-add testkey
Could not add identity "testkey": agent refused operation
All other gpg functions work properly (encrypting/decrypting/signing). Also, the keys I generate work fine if I use them directly with ssh, and they work properly if I run the ssh-agent that came with openssh.
The documentation says that ssh-add should add keys to ~/.gnupg/sshcontrol, but obviously nothing is happening.
My question: What's the easiest way to load a key generated by openssh's ssh-keygen into gpg-agent, and can someone please cut and paste a terminal session showing how this works?
|
The answer was apparently to run:
echo UPDATESTARTUPTTY | gpg-connect-agent
I have no idea why the pinentry program worked fine for other uses such as decrypting files, but didn't work for ssh-add.
While this now works, it also makes a copy of the ssh private key that doesn't show up under gpg -Kv, and furthermore doesn't seem to allow you to change the passphrase on your private key (since you can't edit it with --edit-key). Basically I'm pretty unhappy with the way gpg-agent provides low visibility into where your secrets are being copied. If you hit this question because you hoped gpg-agent might be a better alternative to ssh-agent, then I'd encourage you to stick to ssh-agent instead of trying out my answer. The main reason to prefer gpg-agent is if you need to for smart-card use.
| gpg-agent refuses SSH keys with ssh-add reporting "agent refused operation" |
1,485,634,653,000 |
I have server script that automatically pulls down and installs a github repository. As part of the script, I'm running ssh-keyscan -H github.com >> ~/.ssh/known_hosts as the git user to automatically accept github's RSA key prior to checking out the repo.
I have successfully used this same script in a local vagrant instance, as well as on several servers. However, on one of the servers this doesn't work, because ssh-keyscan -H github.com doesn't return any output (I've tried this as the git user, my personal user, and as root, and the command acts the same). I can ping github.com, so it's not a connection issue; I can also run ssh-keyscan successfully on another server in the same network. I've tried upgrading SSH to see if that might be the issue, but it is already on the latest version for my distribution (CentOS 7).
Where would be a good place to start in troubleshooting this? I've tried searching StackExchange for issues related to 'ssh-keyscan', but I haven't yet found anything that fits this particular problem.
|
This does sound like a network problem to me.
The first thing that I would do is try telnetting to various SSH servers on port 22, something like the following:
$ telnet local-git-server 22
followed by:
$ telnet github.com 22
When you run this, you should see similar output to the following:
Escape character is '^]'.
SSH-2.0-OpenSSH_6.0p1 Debian-4+deb7u2
This is a good indication that ssh is permitted without any firewall restrictions.
What was the end result from ssh-keyscan?
What did it print, if anything?
Does the telnet hang for several seconds? Do you get a connection refused or connection rejected response?
If you run netstat -an --tcp do you see several TCP entries that are in SYN_SENT state? If so, this would indicate there is something blocking at the network layer
| ssh-keyscan has no output |
1,485,634,653,000 |
I’m having fun with OpenSSH, and I know the /etc/ssh directory is for the ssh daemon and the ~/.ssh directory is for a particular user.
Both directories contain private and public keys:
But what is the difference between those keys? I’m confused because the ones I use as a user is in my home directory, and what are the roles of the keys found in /etc/ssh?
|
/etc/ssh provides configuration for the system: default configuration for users (/etc/ssh/ssh_config), and configuration for the daemon (/etc/ssh/sshd_config). The various host files in /etc/ssh are used by the daemon: they contain the host keys, which are used to identify the server — in the same way that users are identified by key pairs (stored in their home directory), servers are also identified by key pairs. Multiple key pairs are used because servers typically offer multiple types of keys: RSA, ECDSA, and Ed25519 in your case. (Users can also have multiple keys.)
The various key files are used as follows:
your private key, if any, is used to identify you to any server you’re connecting to (it must then match the public key stored in the server’s authorized keys for the account you’re trying to connect to);
the server’s private key is used by the client to identify the server; such identities are stored in ~/.ssh/known_hosts, and if a server’s key changes, SSH will complain about it and disable certain features to mitigate man-in-the-middle attacks;
your public key file stores the string you need to copy to remote servers (in ~/.ssh/authorized_keys); it isn’t used directly;
the server’s public key files store strings you can copy to your known hosts list to pre-populate it; it also isn’t used directly.
The last part isn’t used all that often; the default SSH model is known as “TOFU” (trust on first use): a connection is trusted by default the first time it’s used, and SSH only cares about unexpected changes. In some cases though it’s useful to be able to trust the first connection too: a server’s operator can communicate the server’s public keys, and users can add these to their known hosts before the first connection.
See the ssh_config and sshd_config manpages for details (man ssh_config and man sshd_config on your system). The format used for known hosts is described in the sshd manpage.
| What is the difference between /etc/ssh/ and ~/.ssh? |
1,485,634,653,000 |
~/.ssh/authorized_keys[2] contains the list of public keys.
Unfortunately, each public key does not specify the key strength ( number of bits ).
Is there a utility that can process this file line by line and output the key strength?
I checked man pages for ssh-keygen, but it looks like it would only work with private keys.
Also, is there a tool that would output sha1 hash the same way as it is displayed in pageant Putty tool?
The format I am looking for:
Key Algorithm Strength Hash Comment
ssh-rsa 2048 00:11:22:33:44:55:66:77:88:99:aa:bb:cc:dd:ee:ff user1@host1
ssh-rsa 2048 11:22:33:44:55:66:77:88:99:aa:bb:cc:dd:ee:ff:11 user2@host2
|
ssh-keygen can do the core of the work (generating a fingerprint from a public key), but it will not automatically process a list of multiple keys as is usually found in an authorized_keys file.
Here is a script that splits up the keys, feeds them to ssh-keygen and produces the table you want:
#!/bin/sh
# usage: authkeys-report <authorized_keys-file>
set -ue
tmp="$(mktemp -t fingerprint-authkeys.XXXXXXXX)"
trap 'rm -f "$tmp"' 0
while read opts key; do
case "$opts" in
[0-9]*|ssh-dss|ssh-rsa)
# not options, first "word" is part of key
key="$opts $key"
;;
esac
echo "$key" >$tmp
set -- $(ssh-keygen -lf "$tmp")
bits="$1" fingerprint="$2"
set -- $key # Note: will mangle whitespace in the comment
case "$1" in
[0-9]*) # SSH v1 key
type=rsa1
shift 3
;;
ssh-rsa|ssh-dss) # SSH v2 key
type="$1"
shift 2
;;
*)
type=unknown
set --
;;
esac
printf '%-14s %-9s %s %s\n' "$type" "$bits" "$fingerprint" "$*"
done <$1
| Given keys in ~/.ssh/authorized_keys format, can you determine key strength easily? |
1,485,634,653,000 |
If I run something like this:
ssh -4 -f -N -T -R "/home/dude/lol.socket:192.168.4.44:4444" dude@someserver -p 22 -i privatekey -o "ExitOnForwardFailure yes" -o ConnectTimeout=5 -o ConnectionAttempts=3 -o ServerAliveInterval=15 -o
And then lets say the connection is closed or dies for whatever reason.. say the computer reboots due to maintenance or error or there's internet connectivity issues or whatever -> we have a big problem. The created socket file /home/dude/lol.socket on the someserver does not get deleted by sshd. So as the reverse tunnel initiator is recovering and tries to recreate the tunnel it can't because:
Error: remote port forwarding failed for listen path /home/dude/lol.socket
On the server side you get something like:
error: bind: Address already in use
error: unix_listener: cannot bind to path: /home/dude/lol.socket
What would be the supported way / best hack to cleanup the socket after disconnect? Is this a bug in sshd, shouldn't it do that automatically if/when disconnects are noticed?
Backstory:
The idea behind using the sockets is simply that the server is going to handle n "dudes" creating reverse tunnels for m "lol" services in whatever ports and using sockets makes it much easier to ensure that a "dude" can only access and bind to his own sockets, but not other dudes sockets. It also frees me from having to keep record of which dude is using which port to expose which service. And when dude wants to connect to the service on some other server all he needs to know is the name of the service and bind it to some random local port (or socket if he wants to) i.e.
ssh -v -i -4 -N -T -L "127.0.0.1:3334:/home/dude/lol.sock" -p 22
dude@someserver -o "ExitOnForwardFailure yes" -o ConnectTimeout=5 -o
ConnectionAttempts=3 -o ServerAliveInterval=15 -o
ServerAliveCountMax=3
There's no need to know some magic port number that the reverse tunnel on the server is suppose to be running on. So, if you have better ideas how to solve this issue I'm all ears.
Tested with client/server both running Debian 9 (client actually on mac inside docker container) using openssh-client/server version 7.4p1-10+deb9u2
|
TL;DR;
The solution is to set the value of StreamLocalBindUnlink to yes in sshd configuration on the server: sudo sh -c 'echo "StreamLocalBindUnlink yes" >> /etc/ssh/sshd_config'.
Long story
The reason this happens is because unix socket files are not automatically removed when the socket is closed. They need to be manually cleaned up when closing if this is desired by calling remove/ unlink with the filepath, but openssh does not do this. However, as I researched the subject further I came to the realisation that the "best practice" with unix sockets is to unlink right before binding to it (Check this SO answer for more details). And this is exactly what the StreamLocalBindUnlink yes tells sshd to do.
Man page says:
StreamLocalBindUnlink
Specifies whether to remove an existing Unix-domain socket file for local or remote port forwarding before creating a new
one. If the socket file already exists and StreamLocalBindUnlink is not enabled, sshd will be unable to forward the port to
the Unix-domain socket file. This option is only used for port forwarding to a Unix-domain socket file.
The argument must be yes or no. The default is no.
The downside of this approach is that rebinding to the socket is now allowed even if the old connection is still there. Doing this seems to leave the old tunnel hanging in there so that any existing tcp connections going through that remain intact, but all new connections go to the new tunnel. Also the old tunnel seems to be permanently and irreversibly detached from the filesystem socket address and will not be able to receive anymore new connections even if the new tunnel is closed.
References
SO: How can I delete a domain socket file when I exit my application
Discussion about this topic on the openssl-dev mailing list
| How to cleanup SSH reverse tunnel socket after connection closed? |
1,485,634,653,000 |
I would like using ssh tunneling options. For that purpose I use command:
ssh -L 1234:localhost:5678 host
however this logs me into the shell on remote host. Next I tried -f as:
ssh -f -L 8999:localhost:6006 host
but I get error Cannot fork into background without a command to execute.
How can I get only ssh tunneling capabilities and running it in background without unnecessary clutter. My ssh version is OpenSSH_7.2p2, OpenSSL 1.0.2h 3 May 2016
|
Use the -N option
-N Do not execute a remote command. This is useful for just for-
warding ports (protocol version 2 only).
Example
ssh -fN -L 8999:localhost:6006 host
| Cannot tunnel over ssh without command/getting shell [duplicate] |
1,485,634,653,000 |
It seems like the following would work as expected, i.e., that the second rule, having a hostname that matches the first rule, would apply it.
Host *.hostname.com
User myuser
IdentityFile ~/.ssh/myidentity
Host blah
HostName complicated.hostname.com
However typing ssh blah only applies the second rule (and not the user or identity file of the first one).
I have two questions:
Why is this happening?
Is it possible to (simply) do what I am trying to do?
|
From the ssh_config man page:
For each parameter, the first obtained value will be used. The configuration
files contain sections separated by “Host” specifications, and that section is
only applied for hosts that match one of the patterns given in the
specification. The matched host name is the one given on the command line.
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.
Additionally I'd make sure I understand these 2 sections if you're unclear how the Host and PATTERNS function. There is only 1 level of matching going on. This facility is very basic in its regex capabilities, but is still powerful once you grok it.
Host sections
The possible keywords and their meanings are as follows (note that keywords
are case-insensitive and arguments are case-sensitive):
Host Restricts the following declarations (up to the next Host keyword)
to be only for those hosts that match one of the patterns given
after the keyword. If more than one pattern is provided, they
should be separated by whitespace. A single ‘*’ as a pattern can
be used to provide global defaults for all hosts. The host is the
hostname argument given on the command line (i.e. the name is not
converted to a canonicalized host name before matching).
A pattern entry may be negated by prefixing it with an exclamation
mark (‘!’). If a negated entry is matched, then the Host entry is
ignored, regardless of whether any other patterns on the line
match. Negated matches are therefore useful to provide exceptions
for wildcard matches.
See PATTERNS for more information on patterns.
PATTERNS
A pattern consists of zero or more non-whitespace characters, ‘*’ (a
wildcard that matches zero or more characters), or ‘?’ (a wildcard that
matches exactly one character). For example, to specify a set of
declarations for any host in the “.co.uk” set of domains, the following
pattern could be used:
Host *.co.uk
The following pattern would match any host in the 192.168.0.[0-9] network
range:
Host 192.168.0.?
A pattern-list is a comma-separated list of patterns. Patterns within
pattern-lists may be negated by preceding them with an exclamation
mark (‘!’). For example, to allow a key to be used from anywhere within an
organisation except from the “dialup” pool, the following entry
(in authorized_keys) could be used:
from="!*.dialup.example.com,*.example.com"
Layering rules
The problem with your approach is that the pattern that matches the 1st Host section doesn't match the 2nd. I typically do something like this:
Host *
User myuser
IdentityFile ~/.ssh/myidentity
Host blah
HostName complicated.hostname.com
One thing that people don't usually pick up on with these rules is that they can repeat. So what I often times do is have multiple sections and I break them up using Host *'s.
Host *
User user1
Host blah1
HostName complicated1.hostname.com
Host blah2
HostName complicated2.hostname.com
Host *
User user2
| Why are rules not combining in an ssh config file? |
1,485,634,653,000 |
I'm trying to upgrade my ssh server from 2048-bit RSA keys to larger keys, as recommendations are to phase out 2048-bit keys soon.
I generated a new key, then added it to the sshd config, like this:
HostKey /etc/ssh/ssh_host_rsa_key (old 2k-bit key first)
HostKey /etc/ssh/ssh_host_rsa4096_key (new larger key 2nd)
After restarting sshd, I ssh'd to the host, I don't get the identification changed warning, however the new also isn't cached in ~/.ssh/known_hosts. If I put the lines in the opposite order, I get the identification changed warning. Similarly, when I add an ed25519 key, no matter what order I put it in, the client doesn't add the new key to the known hosts file.
This seems to make SSH host key rollover impossible—difficult to believe that's really the case, though, considering security routinely requires upgrading keys.
I know you can just swap the key, then every client needs to run ssh-keygen -R to remove the old key, then manually verify and accept the new key—but that's a real pain, especially if you have a lot of clients connecting or don't administer all the clients. Not to mention, if you don't administer the clients, there is a very good chance they won't actually check the host key and instead just hit Y—so the attempt to improve security will likely actually open you to man-in-the-middle attacks instead.
Is there some way to make SSH host key upgrades work? That is, clients should learn the new more secure key (and also hopefully un-learn the obsolete key). And without giving the host key changed man-in-the-middle warning.
|
The Host Key rotation is supported since OpenSSH 6.8 (both client and server adds support in this version).
So the process should work like this:
Generate and add new keys with the option HostKey newkey (after the existing ones) to the /etc/ssh/sshd_config
Restart sshd
The clients have to set up UpdateHostKeys yes in their configuration (either globally, or per-host)
The connecting clients will pick up all the new keys
After some time (months?) you can remove the old keys from the sshd_config and restart sshd
The clients (that connected during the transition period) will already have the new keys (the old will not be removed, which is the only problem here) and they will not show the MitM attack warning.
The new enough-clients will be able to pick up the new keys. This feature is not enabled by default, probably because it is quite new and soon showed some security consideration. But these days, it should be fine to use it.
| How to roll over ssh host keys? |
1,485,634,653,000 |
Why do the "ssh_config(5)" manpages recommend that the ControlPath option should contain at least the %h, %p and %r placeholders in order to uniquely identify each shared connection?
I thought that multiple sessions should share the same socket with a connection to the same host. Wouldn't it make sense then to have a simple definition such as:
ControlPath ~/.cache/ssh/mux/%h
Instead of something like:
ControlPath ~/.cache/ssh/mux/%r@%h:%p
In my understanding with the first definition one connection is shared between multiple sessions with different remote users, to the same remote host, on different remote ports.
I want to have the first defintion in the host default section so that it suffices to say ssh -o ControlMaster=no.
I want to share the connection to the same remote host between all sessions initiated by the same local user regardless of the remote user and remote port. The master client's socket should live beneath the local user's home directory.
|
"I thought that multiple sessions should share the same socket with a connection to the same host."
They can. However, note that if you connect to a host using an existing connection via ControlPath, regardless of which user you intend to log in as, you will be logged in as the original user of the connection. Eg., with no established connection to "somewhere":
ssh -o ControlPath=~/.ssh/%h -o ControlMaster=yes bob@somewhere
This session is bob@somewhere.
ssh -o ControlPath=~/.ssh/%h -o ControlMaster=no sue@somewhere
This session will also be bob@somewhere, because you used the same ControlPath and set ControlMaster=no; if ControlMaster=yes, you'd be logged in as sue, but ssh will have ignored your ControlPath argument, as implied in man ssh_config:
Additional sessions can connect to this socket using the same ControlPath with ControlMaster set to 'no'.
As evidence of this, if ControlMaster=yes in both cases, when bob exits the ControlPath socket ~/.ssh/somewhere will disappear even though the "sue" session is still running, meaning the sue session never used that socket.
So, if you want to use the same connection, just %h is fine, but beware that you cannot share a connection as multiple different remote users -- ssh won't let you.
| Why not simply use %h in OpenSSH ssh's ControlPath option? |
1,485,634,653,000 |
So, I have a bunch of machines I manage, where I've aliased each of them for ease of access.
This looks like this for each of them in the ssh client config:
Host MACHINE-1075 M1075 m1075 1075
User service
HostName 10.0.100.75
And also:
Match User service
IdentityFile ~/.ssh/service_user
Which allows me to simply type ssh 1075 to get into that machine, with the correct identity file and user automatically.
This works just fine for normal accesses. Sometimes, however, I may need to log in as root for certain tasks. I can accomplish this by explicitly specifying the identity file, e.g. ssh root@1075 -i ~/.ssh/root_user.
This is okay, but what I'd really like to do is to configure SSH to figure out the required identity file from the combination of user and host, allowing me to type ssh root@1075 and do the right thing. I know I can match all uses of the root user and link it up to an identity file with:
Match User root
IdentityFile ~/.ssh/root_user
This doesn't work for my case, however, because there are several groups of machines which may require different credentials for root access, so not all of them should match. Ideally, what I'd like to do is something like:
Match Host 10.0.100.75 && Match User root
IdentityFile ~/.ssh/root_user
But this doesn't seem to work. As a temporary solution, I've simply aliased the machines with root- as a prefix, so I can do ssh root-1075, which isn't too bad, but it's not quite what I want.
This is on Ubuntu 21.10 running OpenSSH 8.4.
|
It's IMHO not entirely clear in man ssh_config, however the syntax for matching multiple conditions appears to be
Match keyword [pattern|pattern-list] keyword [pattern|pattern-list]
where patterns in pattern-list are comma-separated, but keyword pattern pairs are separated from one another by simple whitespace:
Match Host 10.0.100.75 User root
No explicit logical operator like && is supported because all criteria must be satisfied - logical AND is understood.
| Matching both user and host simultaneously in SSH config |
1,485,634,653,000 |
I am using @GarethTheRed 's answer to this question to install fail2ban on a remote CentOS 7 server. I am able to complete all the steps up until tail -f /var/log/fail2ban.log, at which point I get different results than he gets in his answer.
Here are the results I am getting at this step:
[[email protected] ~]# tail -f /var/log/fail2ban.log
2014-12-02 16:55:53,548 fail2ban.server.server[6667]: INFO Changed logging target to /var/log/fail2ban.log for Fail2ban v0.9.0
2014-12-02 16:55:53,550 fail2ban.server.database[6667]: INFO Connected to fail2ban persistent database '/var/lib/fail2ban/fail2ban.sqlite3'
2014-12-02 16:55:54,239 fail2ban.server.database[6667]: WARNING New database created. Version '2'
After the last line, I just get a cursor but no command prompt unless I type Ctrl-C.
When I type systemctl status fail2ban, it tells me that fail2ban is active. When I log out of the system and log back in later, sshd tells me that there have been many failed attempts to login since my last login. So there should be fail2ban logs. But I cannot seem to find them.
Can someone show me how to get this set up so that fail2ban generates logs that I can track?
|
Try installing fail2ban from EPEL. It's packaged for CentOS 7 and you'll get updates as they are released. Installing the rpm form another repo may work (it did in this case) but is not the best way of doing things.
First of all, install the EPEL repository by issuing the following (as root):
yum install epel-release
The above should install EPEL and give you access to many new packages. One of those packages is fail2ban, therefore install it by running:
yum install fail2ban
By default there are no jails configured, therefore to configure a basic sshd jail:
Create/edit the file /etc/fail2ban/jail.local and add:
[sshd]
enabled = true
Start it with:
systemctl start fail2ban
Make it start at boot time:
systemctl enable fail2ban
There used to be a known bug where SELinux would block fail2ban from accessing the log files it needed to do its job. This seems to be fixed in the most recent version of CentOS 7; you shouldn't need to make the changes below.
If you do have this issue, symptoms are nothing appearing in the logs and nothing appearing as failed or blocked in the output of fail2ban-client status sshd.
To check for SELinux error, read the journals with:
journalctl -lfu fail2ban
Watch them for messages such as:
SELinux is preventing /usr/bin/python2.7 from getattr access on the file .
***** Plugin catchall (100. confidence) suggests **************************
If you believe that python2.7 should be allowed getattr access on the file by default.
Then you should report this as a bug.
You can generate a local policy module to allow this access.
Do
allow this access for now by executing:
# grep fail2ban-server /var/log/audit/audit.log | audit2allow -M mypol
# semodule -i mypol.pp
Therefore do as suggested and run:
grep fail2ban-server /var/log/audit/audit.log | audit2allow -M mypol
semodule -i mypol.pp
Then, to be safe, restart fail2ban:
systemctl restart fail2ban
You may even have to repeat the process above until no more error messages appear in the log.
If your server is on the internet then monitor fail2ban-client status sshd. It will soon start to show failed and banned counts if you've caught all the SELinux issues.
Note that you will have to keep an eye on your SELinux policy updates. If a selinux-policy package update appears, it may overwrite the above and you may need to run the above commands again. You'll know if this is the case as fail2ban will stop working again!
| Installing fail2ban on CentOS 7 |
1,485,634,653,000 |
There is a Match group in the SSHD config:
cat /etc/ssh/sshd_config
...
Match Group FOOGROUP
ForceCommand /bin/customshell
...
There are many users on the machine that are in the "FOOGROUP".
My question: How can I exclude a given user that is in the "FOOGROUP" from the "Match Group"?
|
The Match operator can take multiple arguments, allowing very flexible rules. In this case, you could do something like this to achieve what you want.
Match Group FOOGROUP User !username
ForceCommand /bin/customshell
The ! negates the argument passed to the User criterion, so even if the user username is in the group FOOGROUP, the Match will not be successful, and username will not be given the custom shell upon logging in.
| How to exclude from a "Match Group" in SSHD? |
1,485,634,653,000 |
I used to login to a remote machine( I have to root of this machine) using key. Both my local machine and remote machine is in f23. From last few days, I can't login to this machine using key. It is asking for password. Here is the ssh -vvv:
ssh -vvv aveta
OpenSSH_7.1p1, OpenSSL 1.0.2d-fips 9 Jul 2015
debug1: Reading configuration data /home/rudra/.ssh/config
debug1: /home/rudra/.ssh/config line 4: Applying options for aveta
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 56: Applying options for *
debug2: ssh_connect: needpriv 0
debug1: Connecting to phy-aveta.physics.uu.se [130.238.194.143] port 22.
debug1: Connection established.
debug1: identity file /home/rudra/.ssh/id_rsa type 1
debug1: key_load_public: No such file or directory
debug1: identity file /home/rudra/.ssh/id_rsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/rudra/.ssh/id_dsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/rudra/.ssh/id_dsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/rudra/.ssh/id_ecdsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/rudra/.ssh/id_ecdsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/rudra/.ssh/id_ed25519 type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/rudra/.ssh/id_ed25519-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_7.1
debug1: Remote protocol version 2.0, remote software version OpenSSH_7.1
debug1: match: OpenSSH_7.1 pat OpenSSH* compat 0x04000000
debug2: fd 3 setting O_NONBLOCK
debug1: Authenticating to phy-aveta.physics.uu.se:22 as 'rudra'
debug3: hostkeys_foreach: reading file "/home/rudra/.ssh/known_hosts"
debug3: record_hostkey: found key type ECDSA in file /home/rudra/.ssh/known_hosts:16
debug3: load_hostkeys: loaded 1 keys from phy-aveta.physics.uu.se
debug3: order_hostkeyalgs: prefer hostkeyalgs: [email protected],[email protected],[email protected],ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug2: kex_parse_kexinit: [email protected],ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1
debug2: kex_parse_kexinit: [email protected],[email protected],[email protected],ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,[email protected],[email protected],ssh-ed25519,ssh-rsa
debug2: kex_parse_kexinit: [email protected],aes128-ctr,aes192-ctr,aes256-ctr,[email protected],[email protected],arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,[email protected]
debug2: kex_parse_kexinit: [email protected],aes128-ctr,aes192-ctr,aes256-ctr,[email protected],[email protected],arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,[email protected]
debug2: kex_parse_kexinit: [email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],hmac-sha2-256,hmac-sha2-512,hmac-sha1,[email protected],[email protected],[email protected],[email protected],hmac-md5,hmac-ripemd160,[email protected],hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: [email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],hmac-sha2-256,hmac-sha2-512,hmac-sha1,[email protected],[email protected],[email protected],[email protected],hmac-md5,hmac-ripemd160,[email protected],hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: none,[email protected],zlib
debug2: kex_parse_kexinit: none,[email protected],zlib
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit: first_kex_follows 0
debug2: kex_parse_kexinit: reserved 0
debug2: kex_parse_kexinit: [email protected],ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha1
debug2: kex_parse_kexinit: ssh-rsa,ecdsa-sha2-nistp256,ssh-ed25519
debug2: kex_parse_kexinit: [email protected],aes128-ctr,aes192-ctr,aes256-ctr,[email protected],[email protected]
debug2: kex_parse_kexinit: [email protected],aes128-ctr,aes192-ctr,aes256-ctr,[email protected],[email protected]
debug2: kex_parse_kexinit: [email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: kex_parse_kexinit: [email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: kex_parse_kexinit: none,[email protected]
debug2: kex_parse_kexinit: none,[email protected]
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit: first_kex_follows 0
debug2: kex_parse_kexinit: reserved 0
debug1: kex: server->client [email protected] <implicit> none
debug1: kex: client->server [email protected] <implicit> none
debug1: kex: [email protected] need=64 dh_need=64
debug1: kex: [email protected] need=64 dh_need=64
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: ecdsa-sha2-nistp256 SHA256:F34tt6QLRDt6Qm45eHOFhYGS5DSxYrThhR2lbBHNXes
debug3: hostkeys_foreach: reading file "/home/rudra/.ssh/known_hosts"
debug3: record_hostkey: found key type ECDSA in file /home/rudra/.ssh/known_hosts:16
debug3: load_hostkeys: loaded 1 keys from phy-aveta.physics.uu.se
debug3: hostkeys_foreach: reading file "/home/rudra/.ssh/known_hosts"
debug3: record_hostkey: found key type ECDSA in file /home/rudra/.ssh/known_hosts:14
debug3: load_hostkeys: loaded 1 keys from 130.238.194.143
debug1: Host 'phy-aveta.physics.uu.se' is known and matches the ECDSA host key.
debug1: Found key in /home/rudra/.ssh/known_hosts:16
debug2: set_newkeys: mode 1
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug2: set_newkeys: mode 0
debug1: SSH2_MSG_NEWKEYS received
debug1: Roaming not allowed by server
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug2: key: /home/rudra/.ssh/id_rsa (0x562e17c87070),
debug2: key: /home/rudra/.ssh/id_dsa ((nil)),
debug2: key: /home/rudra/.ssh/id_ecdsa ((nil)),
debug2: key: /home/rudra/.ssh/id_ed25519 ((nil)),
debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic,password
debug3: start over, passed a different list publickey,gssapi-keyex,gssapi-with-mic,password
debug3: preferred gssapi-keyex,gssapi-with-mic,publickey,keyboard-interactive,password
debug3: authmethod_lookup gssapi-keyex
debug3: remaining preferred: gssapi-with-mic,publickey,keyboard-interactive,password
debug3: authmethod_is_enabled gssapi-keyex
debug1: Next authentication method: gssapi-keyex
debug1: No valid Key exchange context
debug2: we did not send a packet, disable method
debug3: authmethod_lookup gssapi-with-mic
debug3: remaining preferred: publickey,keyboard-interactive,password
debug3: authmethod_is_enabled gssapi-with-mic
debug1: Next authentication method: gssapi-with-mic
debug1: Unspecified GSS failure. Minor code may provide more information
No Kerberos credentials available
debug1: Unspecified GSS failure. Minor code may provide more information
No Kerberos credentials available
debug1: Unspecified GSS failure. Minor code may provide more information
debug1: Unspecified GSS failure. Minor code may provide more information
No Kerberos credentials available
debug2: we did not send a packet, disable method
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/rudra/.ssh/id_rsa
debug3: send_pubkey_test
debug2: we sent a publickey packet, wait for reply
debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic,password
debug1: Trying private key: /home/rudra/.ssh/id_dsa
debug3: no such identity: /home/rudra/.ssh/id_dsa: No such file or directory
debug1: Trying private key: /home/rudra/.ssh/id_ecdsa
debug3: no such identity: /home/rudra/.ssh/id_ecdsa: No such file or directory
debug1: Trying private key: /home/rudra/.ssh/id_ed25519
debug3: no such identity: /home/rudra/.ssh/id_ed25519: No such file or directory
debug2: we did not send a packet, disable method
debug3: authmethod_lookup password
debug3: remaining preferred: ,password
debug3: authmethod_is_enabled password
debug1: Next authentication method: password
[email protected]'s password:
I have deleted .ssh, .config and .cache from the remote and redo ssh-copy-id, without any help.
To troubleshoot, I have createed another user, did ssh-copy-id and that one is working fine. ssh -vvv for that working machine is:
ssh -vvv [email protected]
OpenSSH_7.1p1, OpenSSL 1.0.2d-fips 9 Jul 2015
debug1: Reading configuration data /home/rudra/.ssh/config
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 56: Applying options for *
debug2: ssh_connect: needpriv 0
debug1: Connecting to phy-aveta.physics.uu.se [130.238.194.143] port 22.
debug1: Connection established.
debug1: identity file /home/rudra/.ssh/id_rsa type 1
debug1: key_load_public: No such file or directory
debug1: identity file /home/rudra/.ssh/id_rsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/rudra/.ssh/id_dsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/rudra/.ssh/id_dsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/rudra/.ssh/id_ecdsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/rudra/.ssh/id_ecdsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/rudra/.ssh/id_ed25519 type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/rudra/.ssh/id_ed25519-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_7.1
debug1: Remote protocol version 2.0, remote software version OpenSSH_7.1
debug1: match: OpenSSH_7.1 pat OpenSSH* compat 0x04000000
debug2: fd 3 setting O_NONBLOCK
debug1: Authenticating to phy-aveta.physics.uu.se:22 as 'rudra2'
debug3: hostkeys_foreach: reading file "/home/rudra/.ssh/known_hosts"
debug3: record_hostkey: found key type ECDSA in file /home/rudra/.ssh/known_hosts:16
debug3: load_hostkeys: loaded 1 keys from phy-aveta.physics.uu.se
debug3: order_hostkeyalgs: prefer hostkeyalgs: [email protected],[email protected],[email protected],ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug2: kex_parse_kexinit: [email protected],ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1
debug2: kex_parse_kexinit: [email protected],[email protected],[email protected],ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,[email protected],[email protected],ssh-ed25519,ssh-rsa
debug2: kex_parse_kexinit: [email protected],aes128-ctr,aes192-ctr,aes256-ctr,[email protected],[email protected],arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,[email protected]
debug2: kex_parse_kexinit: [email protected],aes128-ctr,aes192-ctr,aes256-ctr,[email protected],[email protected],arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,[email protected]
debug2: kex_parse_kexinit: [email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],hmac-sha2-256,hmac-sha2-512,hmac-sha1,[email protected],[email protected],[email protected],[email protected],hmac-md5,hmac-ripemd160,[email protected],hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: [email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],hmac-sha2-256,hmac-sha2-512,hmac-sha1,[email protected],[email protected],[email protected],[email protected],hmac-md5,hmac-ripemd160,[email protected],hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: none,[email protected],zlib
debug2: kex_parse_kexinit: none,[email protected],zlib
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit: first_kex_follows 0
debug2: kex_parse_kexinit: reserved 0
debug2: kex_parse_kexinit: [email protected],ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha1
debug2: kex_parse_kexinit: ssh-rsa,ecdsa-sha2-nistp256,ssh-ed25519
debug2: kex_parse_kexinit: [email protected],aes128-ctr,aes192-ctr,aes256-ctr,[email protected],[email protected]
debug2: kex_parse_kexinit: [email protected],aes128-ctr,aes192-ctr,aes256-ctr,[email protected],[email protected]
debug2: kex_parse_kexinit: [email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: kex_parse_kexinit: [email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: kex_parse_kexinit: none,[email protected]
debug2: kex_parse_kexinit: none,[email protected]
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit: first_kex_follows 0
debug2: kex_parse_kexinit: reserved 0
debug1: kex: server->client [email protected] <implicit> none
debug1: kex: client->server [email protected] <implicit> none
debug1: kex: [email protected] need=64 dh_need=64
debug1: kex: [email protected] need=64 dh_need=64
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: ecdsa-sha2-nistp256 SHA256:F34tt6QLRDt6Qm45eHOFhYGS5DSxYrThhR2lbBHNXes
debug3: hostkeys_foreach: reading file "/home/rudra/.ssh/known_hosts"
debug3: record_hostkey: found key type ECDSA in file /home/rudra/.ssh/known_hosts:16
debug3: load_hostkeys: loaded 1 keys from phy-aveta.physics.uu.se
debug3: hostkeys_foreach: reading file "/home/rudra/.ssh/known_hosts"
debug3: record_hostkey: found key type ECDSA in file /home/rudra/.ssh/known_hosts:14
debug3: load_hostkeys: loaded 1 keys from 130.238.194.143
debug1: Host 'phy-aveta.physics.uu.se' is known and matches the ECDSA host key.
debug1: Found key in /home/rudra/.ssh/known_hosts:16
debug2: set_newkeys: mode 1
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug2: set_newkeys: mode 0
debug1: SSH2_MSG_NEWKEYS received
debug1: Roaming not allowed by server
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug2: key: /home/rudra/.ssh/id_rsa (0x55c98f7eb080),
debug2: key: /home/rudra/.ssh/id_dsa ((nil)),
debug2: key: /home/rudra/.ssh/id_ecdsa ((nil)),
debug2: key: /home/rudra/.ssh/id_ed25519 ((nil)),
debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic,password
debug3: start over, passed a different list publickey,gssapi-keyex,gssapi-with-mic,password
debug3: preferred gssapi-keyex,gssapi-with-mic,publickey,keyboard-interactive,password
debug3: authmethod_lookup gssapi-keyex
debug3: remaining preferred: gssapi-with-mic,publickey,keyboard-interactive,password
debug3: authmethod_is_enabled gssapi-keyex
debug1: Next authentication method: gssapi-keyex
debug1: No valid Key exchange context
debug2: we did not send a packet, disable method
debug3: authmethod_lookup gssapi-with-mic
debug3: remaining preferred: publickey,keyboard-interactive,password
debug3: authmethod_is_enabled gssapi-with-mic
debug1: Next authentication method: gssapi-with-mic
debug1: Unspecified GSS failure. Minor code may provide more information
No Kerberos credentials available
debug1: Unspecified GSS failure. Minor code may provide more information
No Kerberos credentials available
debug1: Unspecified GSS failure. Minor code may provide more information
debug1: Unspecified GSS failure. Minor code may provide more information
No Kerberos credentials available
debug2: we did not send a packet, disable method
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/rudra/.ssh/id_rsa
debug3: send_pubkey_test
debug2: we sent a publickey packet, wait for reply
debug1: Server accepts key: pkalg ssh-rsa blen 279
debug2: input_userauth_pk_ok: fp SHA256:xT3VPQUunB3Nv/Pmi6C6Sroc0fa9SlKcQ4d0eF2vxzI
debug3: sign_and_send_pubkey: RSA SHA256:xT3VPQUunB3Nv/Pmi6C6Sroc0fa9SlKcQ4d0eF2vxzI
debug1: Authentication succeeded (publickey).
Authenticated to phy-aveta.physics.uu.se ([130.238.194.143]:22).
debug1: channel 0: new [client-session]
debug3: ssh_session2_open: channel_new: 0
debug2: channel 0: send open
debug1: Requesting [email protected]
debug1: Entering interactive session.
debug1: client_input_global_request: rtype [email protected] want_reply 0
debug2: callback start
debug2: fd 3 setting TCP_NODELAY
debug3: ssh_packet_set_tos: set IP_TOS 0x10
debug2: client_session2_setup: id 0
debug2: channel 0: request pty-req confirm 1
debug1: Sending environment.
debug3: Ignored env XDG_VTNR
debug3: Ignored env XDG_SESSION_ID
debug3: Ignored env HOSTNAME
debug3: Ignored env SHELL
debug3: Ignored env TERM
debug3: Ignored env XDG_MENU_PREFIX
debug3: Ignored env VTE_VERSION
debug3: Ignored env HISTSIZE
debug3: Ignored env XCRYSDEN_SCRATCH
debug3: Ignored env WINDOWID
debug3: Ignored env QTDIR
debug3: Ignored env QTINC
debug3: Ignored env QT_GRAPHICSSYSTEM_CHECKED
debug3: Ignored env XCRYSDEN_TOPDIR
debug3: Ignored env USER
debug3: Ignored env LS_COLORS
debug3: Ignored env DESKTOP_AUTOSTART_ID
debug3: Ignored env SSH_AUTH_SOCK
debug3: Ignored env SESSION_MANAGER
debug3: Ignored env PATH
debug3: Ignored env MAIL
debug3: Ignored env DESKTOP_SESSION
debug3: Ignored env QT_IM_MODULE
debug3: Ignored env XDG_SESSION_TYPE
debug3: Ignored env PWD
debug1: Sending env XMODIFIERS = @im=ibus
debug2: channel 0: request env confirm 0
debug1: Sending env LANG = en_GB.UTF-8
debug2: channel 0: request env confirm 0
debug3: Ignored env MODULEPATH
debug3: Ignored env GDM_LANG
debug3: Ignored env LOADEDMODULES
debug3: Ignored env GDMSESSION
debug3: Ignored env SSH_ASKPASS
debug3: Ignored env HISTCONTROL
debug3: Ignored env HOME
debug3: Ignored env XDG_SEAT
debug3: Ignored env SHLVL
debug3: Ignored env GNOME_DESKTOP_SESSION_ID
debug3: Ignored env XBANDPATH
debug3: Ignored env XDG_SESSION_DESKTOP
debug3: Ignored env LOGNAME
debug3: Ignored env QTLIB
debug3: Ignored env DBUS_SESSION_BUS_ADDRESS
debug3: Ignored env MODULESHOME
debug3: Ignored env LESSOPEN
debug3: Ignored env WINDOWPATH
debug3: Ignored env XDG_RUNTIME_DIR
debug3: Ignored env DISPLAY
debug3: Ignored env XDG_CURRENT_DESKTOP
debug3: Ignored env XAUTHORITY
debug3: Ignored env BASH_FUNC_module()
debug3: Ignored env BASH_FUNC_scl()
debug3: Ignored env _
debug2: channel 0: request shell confirm 1
debug2: callback done
debug2: channel 0: open confirm rwindow 0 rmax 32768
debug2: channel_input_status_confirm: type 99 id 0
debug2: PTY allocation request accepted on channel 0
debug2: channel 0: rcvd adjust 2097152
debug2: channel_input_status_confirm: type 99 id 0
debug2: shell request accepted on channel 0
Last login: Mon Oct 12 12:33:15 2015 from 130.238.194.90
[rudra2@phy-aveta ~]$ debug2: client_check_window_change: changed
debug2: channel 0: request window-change confirm 0
I am clueless why in same local-remote combination, one is working and other is not.
EDIT .ssh/config for the failed one is:
Host aveta
User rudra
Hostname phy-aveta.physics.uu.se
ForwardX11 yes
There is no ssh/.config entry for rudra2, i.e. that worked.
Ans to Paul
in my local machine I have:
tree .ssh/
.ssh/
├── authorized_keys
├── config
├── environment
├── id_rsa
├── id_rsa.pub
└── known_hosts
In both the remote user, I only have authorized_keys. And both are identical.
[root@phy-aveta rudra2]# diff .ssh/authorized_keys /home/rudra/.ssh/authorized_keys
[root@phy-aveta rudra2]#
Edit 2: Without using ssh/.configI have commented out the part for first user in .ssh/config.
http://ur1.ca/nzndx is the ssh -vvv for that. It is still asking for password
Edit: Permission
The first user...failed one
#ls -al /home/rudra/|grep .ssh
drwx------. 2 rudra rudra 4096 Oct 12 14:16 .ssh
$ls -alF .ssh/
total 12K
drwx------. 2 rudra rudra 4.0K Oct 12 14:16 ./
drwxrwxr-x. 36 rudra rudra 4.0K Oct 12 14:30 ../
-rw-------. 1 rudra rudra 394 Oct 10 12:01 authorized_keys
For 2nd user
# ls -al /home/rudra2/|grep .ssh
drwx------. 2 rudra2 rudra2 4096 Oct 12 14:16 .ssh
$ ls -alF .ssh/
total 12
drwx------. 2 rudra2 rudra2 4096 Oct 12 14:16 ./
drwx------. 4 rudra2 rudra2 4096 Oct 12 14:14 ../
-rw-------. 1 rudra2 rudra2 394 Oct 11 09:57 authorized_keys
|
There it is. Group has write access to ~rudra:
$ls -alF .ssh/ total 12K
drwx------. 2 rudra rudra 4.0K Oct 12 14:16 ./
drwxrwxr-x. 36 rudra rudra 4.0K Oct 12 14:30 ../
-rw-------. 1 rudra rudra 394 Oct 10 12:01 authorized_keys
Thus, sshd refuses to trust the files in ~rudra, and does not use ~rudra/.ssh/authorized_keys, even though its permissions are correct.
chmod g-w ~rudra ought to fix it.
| Can't login to a remote machine with key |
1,485,634,653,000 |
I'm trying to test if ~/.ssh/id_rsa is actually password protected.
When you run ssh-keygen you can choose an empty password, and I'm trying to detect this.
Is that possible with a one-liner?
|
If you open the private key file in text editor you will be able to see ENCRYPTED in the second line of the RSA/DSA key file.
For example:
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-128-CBC,373B504621779D53C72BADE597C531A0
| Test if SSH private key has password protection |
1,485,634,653,000 |
In my environment, actual .ssh directory exists on external device and links from it to ~/.ssh with a symbolic link. Using openssh as client is working without problem, but sshd does not allow to authentication with public key inside it.
Is there any method to use .ssh directory on external device?
journalctl -u sshd
Authentication refused: bad ownership or modes for directory /pool/secure/ssh
permissions
$ ls -ld ~/.ssh
lrwxrwxrwx. 1 foobar foobar 28 Mar 7 19:59 .ssh -> /pool/secure/ssh
$ ls -l /pool/secure/ssh
-rw------- 1 foobar foobar 381 Jun 29 15:01 authorized_keys
-rw------- 1 foobar foobar 292 Jun 29 15:01 config
-rw-------. 1 foobar foobar 5306 Jun 23 02:16 known_hosts
$ ls -ld /pool/secure/ssh
drwx------. 2 foobar foobar 8 Jun 29 15:01
version
$ ssh -V
OpenSSH_7.4p1, OpenSSL 1.0.2k-fips 26 Jan 2017
Added at 2017-06-29 (Tips)
OpenBSD and FreeBSD can modify access permission of symlink by chmod. But Linux does not have system call doing that operation.
stat(2) follow the link.
Base Specifications Issue 7 unspecified the value of the file mode bits returned in the st_mode field.
Solved at 2017-06-30
auth_secure_path have the answer. This function check permissions of file and directory, the range include parent directory. It continues to check if correct permissions (only owner can write) are set, until passing the home or root .
ex) general environment
/home/foobar/.ssh (raise error if group and other can write)
/home/foobar (same)
break!
ex) special environment (like me)
/home/foobar/.ssh -> /pool/secure/ssh
/pool/secure/ssh (raise error if group and other can write)
/pool/secure (same)
/pool (same)
/ (same)
break!
|
It is a permissions issue.
You need to check permissions for all directories above and including foobar's home, and also all directories above the target .ssh directory on your external device. Apart from foobar and the target .ssh directories, all others must be owned by root and not writeable by anyone else.
You may also have an SELinux issue. You can check the SELinux security context of files and directories with the -Z flag:
[sheepd0g@dogpound ~]$ ls -ZA
drwxr-xr-x. root root system_u:object_r:home_root_t:s0 ..
drwxrwxr-x. sheepd0g sheepd0g unconfined_u:object_r:user_home_t:s0 20170620-auditlogs
-rw-rw-r--. sheepd0g sheepd0g unconfined_u:object_r:user_home_t:s0 random.dat
drwx------. sheepd0g sheepd0g unconfined_u:object_r:ssh_home_t:s0 .ssh
A couple things to note:
The period at the end of the permission mode fields means SELinux context is active for that file.
Notice the Type field for the .ssh folder is different (ssh_home_t).
SELinux objects, types, policies, and settings may not be the same across distributions, or even major versions. What works for RHEL6 may not for, say SUSE 10 or Debian 6 (I'm not sure Debian 6 even has SELinux enforcing, out of the box...)
Regardless, this is a good place to look if all else fails. You can check if SELinux is in enforcing mode easily enough with the following:
[sheed0g@dogpound ~]$ sudo getenforce
Enforcing
If you suspect SELinux us the issue, you can switch SELinux to Permissive mode (policies are enabled, but no action is taken -- just logging/auditing of actions):
[sheepd0b@dogpound ~]$ sudo setenforce 0
[sheepd0b@dogpound ~]$ sudo getenforce
Permissive
If your issue goes away, this is likely the problem.
Please note, there is A LOT more complexity to SELinux than what is represented here. If your .ssh/ is on an NFS share you will be required to make more changes with boolean settings for SELinux.
Here are two good references for SELinux:
CentOS wiki entry on SELinux
Red Hat Enterprise Linux 7 SELinux guide
| OpenSSH refused .ssh directory with a symbolic link |
1,635,063,773,000 |
Since OpenSSH release 8.8 ssh-rsa is disabled in OpenSSH sshd:
$ ssh-audit 1.2.3.4
# algorithm recommendations (for OpenSSH 8.8)
...
(rec) +ssh-rsa -- key algorithm to append
...
Archlinux forum thread "Latest sshd not accepting key algorithms" recommends:
$ grep PubkeyA /etc/ssh/sshd_config
#PubkeyAuthentication yes
PubkeyAcceptedKeyTypes=+ssh-rsa
Though that configuration snippet doesn't enable ssh-rsa in openssh-8.8p1-1 on 5.10.74-1-raspberrypi4-ARCH, not even after a restart of sshd.
How to force OpenSSH sshd release 8.8 to enable ssh-rsa?
|
To permit using old RSA keys for OpenSSH 8.8+, add the following lines to your sshd_config:
HostKeyAlgorithms=ssh-rsa,[email protected]
PubkeyAcceptedAlgorithms=+ssh-rsa,[email protected]
Other distributions (then Arch on RPi) might support the more secure xmss keys, which are recommended for use by latest NIST papers
HostKeyAlgorithms=ssh-rsa,[email protected],[email protected],[email protected]
[email protected]
PubkeyAcceptedAlgorithms=+ssh-rsa,[email protected],[email protected],[email protected]
| How to enable ssh-rsa in sshd of OpenSSH 8.8? |
1,635,063,773,000 |
I'm running the below command, and monitoring the output file on the other system:
ssh $ip_address 'for n in 1 2 3 4 5; do sleep 10; echo $n >>/tmp/count; done'
If I kill the ssh command using ^C or by just killing the terminal I'm logged in on, I'd expect the remote command to terminate, too. This doesn't happen, though: /tmp/count gets all the numbers 1–5 regardless, and ps -ejH shows the shell and its sleep child continues running.
Is this expected behaviour, and is it documented anywhere? Can I disable it? From reading around, I'd expected to have to explicitly enable this sort of behaviour with nohup, not for it to be the default.
I've taken a look through the man pages for ssh and sshd, but not spotted anything obvious, and Google points me at instructions for turning this behaviour on, not for turning it off.
I'm running Red Hat Enterprise Linux 6.2, with a root login and bash shell on both systems.
|
uther's answer tells you to allocate a terminal but doesn't explain why. The reason is not specific to ssh, it is a matter of signal generation and propagation. I invite you to read What causes various signals to be sent? for more background.
On the remote host, there are two relevant processes:
an instance of the ssh daemon (sshd), which is relaying the input and output of the remote program to the local terminal;
a shell, which is running that for loop.
The shell can die either naturally when it reaches the end of the loop or experiences a fatal error, or to a signal. The question is, why would the shell receive a signal?
If the remote shell is connected to sshd over pipes, which is what happens when you specify a command on the ssh command line, then it will die of a SIGPIPE if sshd exits and the shell tries to write to the pipe. As long as the shell isn't writing to the pipe, it won't receive a SIGPIPE. Here, the shell is never writing anything to its standard output, so it can live forever.
You can pass the -t option to ssh, to tell it to emulate a terminal on the remote side and run the specified command in this terminal. Then, if the SSH client disappears, sshd closes the connection and exits, destroying the terminal. When the terminal device goes away, any process running in it receives a SIGHUP. So if you kill the SSH client (with kill, or by closing the terminal that the client is running in), the remote shell is SIGHUPped.
If you pass the -t option, SSH also relays SIGINT. If you press Ctrl+C, then the remote shell receives a SIGINT.
| ssh command unexpectedly continues on other system after ssh terminates |
1,635,063,773,000 |
I have a Raspberry Pi (RPi) and I am making remote connections to it using ssh. I have managed to set up ssh correctly such that I can access the RPi both from a local area network and from the internet (using a specific port that I opened on my router).
Assuming an user name john and a RPi named raspi:
Inside LAN access
ssh [email protected]
ssh john@raspi
ssh raspi
Outside LAN access
ssh -p 1234 [email protected]
ssh -p 1234 12.345.67.89
But how can I simply do ssh raspi from outside my LAN?. Is there a way to configure raspi to point to two IP-adresses, one in a LAN and one over the internet?
What I basically want is to access my RPi in a single way, no matter whether I am at home or work.
|
Looking closer at your question, it appears you're using the same computer from both in- and outside of the LAN. I have revised my answer accordingly:
In your ~/.ssh/config, add:
Host raspi-wan
HostName 12.34.56.78
User john
Port 1234
Host raspi-lan
HostName 192.168.1.2
User john
Port 22
Then, you can ssh raspi-wan from outside the LAN, or ssh raspi-lan from inside the LAN without faffing about with DNS servers or editing /etc/hosts for all users, or even needing to do anything as root. If you want the name raspi to resolve differently depending upon where you are, that will probably require some shell scripting magic to detect your network and act accordingly.
| SSH access from inside and outside a LAN using the same terminal command |
1,635,063,773,000 |
I am in a situation where several users are sharing the same user account on a remote machine. I have a "personal" directory where I wrote my own .zshrc file, and I would like to have a way to:
Start a ssh session in the remote machine with directives from my ssh config file
(e.g. ControlMaster auto)
This session runs a Z shell
It runs a .zshrc in my "personal" directory (not on the shared user's home directory)
It would be nice to have an alias or a simple way of starting such ssh sessions (that's why I thought about using the OpenSSH's config file), but I am open to any other ideas!
Using OpenSSH's config file?
I read on the OpenSSH's ssh_config man page that I can use the directive LocalCommand to specify a command to run locally after successfully connecting to the server. This made me think there may be a way to tell the config file what command to run remotely after connecting to the server, but there doesn't seem to be any.
|
The most obvious way to run a command remotely is to specify it on the ssh command line. The ssh command is always interpreted by the remote user's shell.
ssh [email protected] '. ~/.profile; command_that_needs_environment_variables'
ssh -t [email protected] '. ~/.profile; exec zsh'
Shared accounts are generally a bad idea; if at all possible, get separate accounts for every user. If you're stuck with a shared account, you can make an alias:
ssh -t [email protected] 'HOME=~/bob; . ~/.profile; exec zsh'
If you use public key authentication (again, recommended), you can define per-key commands in ~/.ssh/authorized_keys. See this answer for more explanations. Edit the line for your key in ~/.ssh/authorized_keys on the server (all on one line):
command="HOME=$HOME/bob;
if [ -n \"$SSH_ORIGINAL_COMMAND\" ]; then
eval \"$SSH_ORIGINAL_COMMAND\";
else exec \"$SHELL\"; fi" ssh-rsa AAAA…== [email protected]
| ssh, start a specific shell, and run a command on the remote machine? |
1,635,063,773,000 |
Basically the entire question is in the headline: Does ssh send the password over the network? Presuming of course that login via username and password is used.
I'm asking because if ssh doesn't send the password over the network, a man in the middle can't get the user's password even if the user adds the alleged host to their known_hosts file.
Someone said it has to, so I wrote down a counter example in a comment. Since the question of how else it could possibly work now came up repeatedly, I'm copying that comment here.
The server can tell the client which hash to use. [The same one which is used to hash the passwords in the server's shadow file.] The client can then calculate the hash ψ which should be in the server's shadow file but let's call the one on the server ψ'. So both the server and the client know ψ. The client can then pick a random salt σ an send (hash(ψ.σ), σ) (where . is the concatenation operator) to the server. The server then hashes ψ'.σ and checks whether the first element of the tuple it received from the client matches that hash. If it does, the client knows the password.
|
If you're using password authentication, then SSH sends the password over the network. The connection is encrypted, so eavesdroppers can't see the password. The connection is authenticated, provided that you don't click blindly through a “The authenticity of … can't be established” message, so your password won't be sent to anyone except the legitimate server.
The boring answer to “why” is that this is what the SSH protocol requires.
The less boring answer is that password authentication has to work that way. There are ways to perform authentication that don't work this way but this is no longer simple password authentication.
Most authentication protocols that are more advanced than simple password authentication have the nice property that the client doesn't send any secret data to the server that a malicious server could use to impersonate the user on some third server. With SSH public key authentication, the most common SSH authentication method other than passwords, this works because the client sends a signature (requiring the private key) of data that includes the session identifier; if the malicious server tried to authenticate to a third server, it would have to generate a signature of data including a different session identifier, which it would be unable to do without the private key that stays on the client.
Note that if you use public key authentication, and you have to type a password to use the key, this is not password-based authentication. The password to use the key is used exclusively on the client side, to read the key from the key file. When using public key authentication, the server does not know or care whether the key was stored in an encrypted file.
Password authentication requires sending the password to the server. Sending a hash of the password instead of the password itself does not help, because then the password becomes the hash: an attacker wouldn't need to find the actual password, only the hash. An attacker could attack by finding the actual password, so there is no improvement. But if the attacker found the hash but not the password, in your proposed scheme, that would be enough. In contrast, with normal password-based authentication, the attacker must know the password, knowing the hash is not good enough, and if the password is strong enough then the attacker won't be able to find the password from the hash. In practice, the reason the attacker might know the hash but not the password is that the attacker managed to extract the database of password hashes from the server, possibly from an unprotected backup or via a vulnerability on the server. Such vulnerabilities on websites make the news pretty often.
Your proposed protocol is less good than the standard one. Don't roll your own crypto!
| Does ssh send the password over the network? |
1,635,063,773,000 |
In the example below what do the channel numbers correspond to? Which are on the server? Which are on the client?
$ ssh -L1570:127.0.0.1:8899 root@thehost
Password:
Last login: Fri Aug 9 13:08:44 2013 from theclientip
Sun Microsystems Inc. SunOS 5.10 Generic January 2005
You have new mail.
# channel 2: open failed: administratively prohibited: open failed
channel 3: open failed: administratively prohibited: open failed
channel 2: open failed: administratively prohibited: open failed
The ssh client is running on Windows 7 and the server has a Tomcat server running on port 8899.
Tomcat is not listening on 127.0.0.1 on the remote machine so if I change the command to ssh -L1570:thehostpublicip:8899 root@thehost the port forward works. So I know that port forwarding seems to be working just fine on the server.
my sshd config file contains the following two lines:
# Port forwarding
AllowTcpForwarding yes
# If port forwarding is enabled, specify if the server can bind to INADDR_ANY.
# This allows the local port forwarding to work when connections are received
# from any remote host.
GatewayPorts yes
I'm trying to setup port forwarding for another process not Tomcat and I get the error messages similar to the stuff above so I'm trying to understand the meaning of the error messages.
|
From the SSH Protocol documentation, regarding channels:
All terminal sessions, forwarded connections, etc., are channels.
Either side may open a channel. Multiple channels are multiplexed
into a single connection.
Channels are identified by numbers at each end. The number referring
to a channel may be different on each side. Requests to open a
channel contain the sender's channel number. Any other channel
related messages contain the recipient's channel number for the
channel.
Channels are flow-controlled. No data may be sent to a channel until
a message is received to indicate that window space is available.
Port forwarding
The command you have looks fine. Are you sure that the service you're trying to connect to is up and accepting connections? The channel errors would seem to indicate that it's not.
What are my active channels?
If you have an active ssh connection you can use the following key combination to get help:
Shift+~ followed by Shift+?
$ ~?
Supported escape sequences:
~. - terminate connection (and any multiplexed sessions)
~B - send a BREAK to the remote system
~C - open a command line
~R - Request rekey (SSH protocol 2 only)
~^Z - suspend ssh
~# - list forwarded connections
~& - background ssh (when waiting for connections to terminate)
~? - this message
~~ - send the escape character by typing it twice
(Note that escapes are only recognized immediately after newline.)
debug2: channel 2: written 480 to efd 8
You can then use this key combination to get a list of the active channels:
Shift+~ followed by Shift+#
$ ~#
The following connections are open:
#2 client-session (t4 r0 i0/0 o0/0 fd 6/7 cc -1)
debug2: channel 2: written 93 to efd 8
| What do the channel numbers in ssh error message refer to? |
1,635,063,773,000 |
My google search results little helpful so I asked here.
My Ubuntu server now has many duplicated entries in both files ~/.ssh/authorzied_keys and ~/.ssh/known_hosts
I wonder if there is a command/utility to remove those duplicated lines and list them once only?
|
The commandline utilities are called uniq and sort. You can simply pipe the file through them to get only unique entries:
sort ~/.ssh/authorized_keys | uniq > ~/.ssh/authorized_keys.uniq
and then replace the old file with the new one:
mv ~/.ssh/authorized_keys{.uniq,}
The ~/.ssh/known_hosts are handled by ssh itself and should not contain any duplicates (if you modified it by hand, it can and then you can use the same approach as above).
| How to clear duplicated entries in SSH known_hosts and authorized_keys files? |
1,635,063,773,000 |
Quick version:
ssh & scp work from my desktop and laptop computers. From termux on my android phone, ssh works but scp does not. In this case, I get an error about "Connection closed".
Expanded version
Originally, when I had asked this question, I had been encountering it while running scp from termux on my android phone while connecting to my Fedora Linux box. And I was quite stumped as ssh had been working so I had provided a lot of debug info. Since I later learned that this issue had nothing at all to do with termux and everything to do with OpenSSH versions, I have attempted to cleanup a lot of the extraneous info dumps and make this more accessible while still preserving relevant error messages for better seo matching.
devices:
device A (computer): Fedora 35 running openssh.x86_64 8.7p1-3.fc35
device B (computer): Fedora 35 running openssh.x86_64 8.7p1-3.fc35
device C (phone): termux on android (I failed to capture the openssh version originally, presumably it was v8.8 or later)
Computers A and B had essentially identical sshd_config files, all 3 essentially the same ~/.ssh/config file contents.
issue:
ssh connections between A->B, B->A, C->A, and C->B all worked fine. I was not interested in connecting to my phone from either computer and never configured sshd on it, so did not test that scenario.
However, for scp running over ssh, I was encountering the following: A->B and B->A worked while C->A and C->B failed with the following error:
$ scp -rp "[email protected]:/home/desktop-user/Pictures/test.jpg" .
scp: Connection closed
debugging:
LOTS of verifying ssh file permissions and ownership, ~/.ssh/config settings, etc. No obvious issues.
I had (temporarily) disabled SELinux and firewalld on both A and B but was still getting the same issue.
Based on this post, I renamed my custom my id_rsa (and id_rsa.pub) filenames to using the default names and edited my corresponding ~/.ssh/config definitions. No change.
Instead of (from C) trying to receive/pull a file from the remote, I attempt to push/send a file to the remote. No change.
From C, I made sure all packages were up-to-date. No change.
From C, I ran the scp command with -v flag to give verbose debug info. After redacting hashes and such I added to pastebin. The main thing I saw was that the keys appeared to be accepted but last line indicated that "debug1: Exit status 127". Results online seemed to indicate that scp did not exist on host... but in my case, it was. So still no change.
sshd config of hosts
Again, A and B had essentially the same config
# grep -Pv '^\s*(#|$)' /etc/ssh/sshd_config
Include /etc/ssh/sshd_config.d/*.conf
Port 22
Ciphers [email protected],aes256-ctr
LoginGraceTime 1m
PermitRootLogin no
MaxAuthTries 4
MaxSessions 6
PermitEmptyPasswords no
ChallengeResponseAuthentication no
UsePAM yes
X11Forwarding yes
PrintMotd no
UseDNS yes
AcceptEnv LANG LC_*
Subsystem sftp /usr/lib/openssh/sftp-server
Protocol 2
DenyUsers root docker-user
MACs [email protected],hmac-sha2-512,[email protected],hmac-sha2-256
KexAlgorithms diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group-exchange-sha256
|
Quick version (TL;DR)
Update: For those that just want a quick-and-dirty with minimal reading.
Know:
This actually had nothing to do with Termux - it affects any Linux using OpenSSH 8.8+. I also ran into it on Fedora 35 with OpenSSH 8.7p1
While sftp will work in a pinch, it handles copying of symlinks differently than scp so don't just throw it in a script as a replacement. Better to use rsync.
Recursively copy a directory from remote to local:
# deprecated / insecure (see CVE link below) but works
scp -O -rp -P <port> "<user>@<host_ip>:<SRC_PATH>" "<DST_PATH>"
# secure / recommended by openssh - also works
rsync -saLPz --port <port> -e ssh "<user>@<host_ip>:<SRC_PATH>" "<DST_PATH>"
Recursively copy a directory from local to remote:
# deprecated / insecure (see CVE link below) but works
scp -O -rp -P <port> "<SRC_PATH>" "<user>@<host_ip>:<DST_PATH>"
# secure / recommended by openssh - also works
rsync -saLPz --port <port> -e ssh "<SRC_PATH>" "<user>@<host_ip>:<DST_PATH>"
This works fine for multiple paths too, e.g.
# copy multiple paths
rsync -saLPz --port <port> -e ssh "<SRC_PATH_1>" "<SRC_PATH_2>" "<SRC_PATH_3>" "<user>@<host_ip>:<DST_PATH>"
# copy multiple paths from array
arrPaths=("<SRC_PATH_1>" "<SRC_PATH_2>" "<SRC_PATH_3>");
rsync -saLPz -e ssh "${arrPaths[@]}" "<user>@<host_ip>:<DST_PATH>"
Root Cause
After a lot of hunting online, I finally found an answer here - credit / thanks to manjaro forums users zbe and canyue980 for finding the initial fix and cluing me into what was actually going on.
To quote canyue980:
Thanks for all guys that offer helps! I just found the solution in upper link:
Note: Since OpenSSH 8.8 the scp utility uses the SFTP protocol by default. The -O option must be used to use the legacy SCP protocol.
by using -O option and it works!
scp -O file_name target_dir
and of course you can also add an alias for it in~/.zshrc like this:
alias scp="scp -O"
Indeed, changed my command from:
scp -rp -P 1234 "[email protected]:/home/desktop-user/Pictures/test.jpg" .
To:
scp -rpO -P 1234 "[email protected]:/home/desktop-user/Pictures/test.jpg" .
and it worked like a champ. Will leave this up in hopes it helps someone else.
Security Implications of -O
Security Implications of using -O (that's "Oh" as in OLD - not zero): according to the release notes for openssh 8.8, it sounds like the main risk is that:
Legacy scp/rcp performs wildcard expansion of remote filenames (e.g.
"scp host:* .") through the remote shell. This has the side effect of
requiring double quoting of shell meta-characters in file names
included on scp(1) command-lines, otherwise they could be interpreted
as shell commands on the remote side.
I don't personally see this as a big risk for people used to the old command and running manually or via trusted scripts on home computers. But your risk-assessment / use-cases may be different - especially for business systems or setups that are using unproved / untrusted scripts. This appears to be the case for some as RHEL 9 is deprecating the scp protocol, citing that:
We're making this change because the SCP protocol is decades old, and carries multiple security risks and issues that have no straightforward solutions. New issues are being reported frequently (CVE-2020-15778 is the most recent as of this writing, but we can’t be sure it will be the last) and it is rather difficult to fix them all properly because the protocol is inherently trustworthy of authenticated sessions.
From the above release notes and links, as well as a note on the arch wiki, it seems the intention is to completely deprecate SCP (e.g. the protocol) in favor of alternatives like sftp and rsync (see below). I am unclear of what the intended future of the scp command is, especially in the short-term, but it seems plausible or even likely that it may also get deprecated in the future.
Recommended replacements
To use sftp and rsync as drop-in replacements in scripts, probably rsync is the easier drop-in replacement as it doesn't require any changes on the host whereas at least as of Fedora 35 sftp does.
The commands below should work for sftp as long as you can connect with sftp <user>@<host_ip> just like you would with ssh (connecting this way will put you in the sftp "shell". To exit, use exit). Otherwise, you may have to enable it on the host. For Fedora 35, that process was as follows:
sudo cp -a /etc/ssh/sshd_config /etc/ssh/sshd_config.$(date +'%F_%T').bak
sudo sed -Ei 's~^(Subsystem[ \t]+sftp[ \t]+)(/usr/lib/openssh/sftp-server)~#\1\2\n\1internal-sftp~g' /etc/ssh/sshd_config
sudo systemctl restart sshd
when done you should see something like this (e.g. the sftp server line should be commented out and a new line with internal-sftp add to take its place) :
sudo grep Subsystem /etc/ssh/sshd_config
#Subsystem sftp /usr/lib/openssh/sftp-server
Subsystem sftp internal-sftp
You can also restrict this using groups and chroot if you need increased security, as shown here and here.
Note: scp by default copies the contents of symlinks instead of them as a symlink. Rsync lets you control this behavior by using -l to copy as symlink or -L to copy what is referenced by the symlink. The -a (archive) option will default to -l, unless -L is also specified. sftp will copy the symlink as a link (e.g. the contents pointed to are not copied) and does not provide an option for controlling this behavior as of time of writing. You can verify this by looking at the documentation for the -r option under man scp and man sftp respectively.
Here are a few examples of roughly equivalent commands, which should all be going over SSH and picking up your ~/.ssh/config settings and identities:
Recursively copy a directory from remote to local:
scp -O -rp -P <port> "<user>@<host_ip>:<SRC_PATH>" "<DST_PATH>"
rsync -saLPz --port <port> -e ssh "<user>@<host_ip>:<SRC_PATH>" "<DST_PATH>"
Recursively copy a directory from local to remote:
scp -O -rp -P <port> "<SRC_PATH>" "<user>@<host_ip>:<DST_PATH>"
rsync -saLPz --port <port> -e ssh "<SRC_PATH>" "<user>@<host_ip>:<DST_PATH>"
Corrections for sftp syntax
Edit: 2022-Sep-13: Noticed today while retesting that the commands I had for sftp were giving errors, so I am moving them out from the above and adding some disclaimers. I don't personally recommend sftp as a replacement for scp anyway due to the differences I mentioned above in how they handle copying when symlinks are involved.
I was specifically interested in using this as a replacement in scripts. If you are only needing interactive mode, don't mind making a "batch" instruction file for sftp, or have rsync installed on all of the machines you'll be using then you probably won't need to go this far. My notes below are partially based this answer, with some additional testing done by me.
My biggest complaint here (other than sftp using different syntax for upload vs download) is the very poor documentation. Looking at man sftp, the syntax isn't documented at all (meaning that while the tool can be used non-interactively, it is only documented for use in batch and interactive modes, and stepping outside those use-cases, while supported, is not documented). The man page gives NO examples of common usage or even a website for more detailed documentation as many of the GNU tools do. And sftp -h provides less than the man page. Literally, if it weren't for search engines and sites like this and I would have completely given up on sftp as an option altogether.
1. Local pull (e.g. from local terminal, download files from remote to local)
This is mostly straight-forward and works somewhat similarly to scp other than the differences noted above (e.g. symlinks) and slightly different syntax. And that one of the variants will result in an interactive prompt.
# Download a single file with same name to current dir
sftp -pC -P <port> "<user>@<host_ip>:<SRC_PATH>"
# or
sftp -pC -P <port> "<user>@<host_ip>:<SRC_PATH>" .
# Download a single file to name and path in "<DST_PATH>"
sftp -pC -P <port> "<user>@<host_ip>:<SRC_PATH>" "<DST_PATH>"
# Download a folder and all of its contents,
# keep the same name as the remote and save to current dir
# note that any symlinks will copy only the symlink itself
# and NOT the data the link references
sftp -rpC -P <port> "<user>@<host_ip>:<SRC_PATH>" .
# Now if you omit "<DST_PATH>" entirely like you can with
# the single-file version (first command in this code-block)
# you instead drop to an interactive prompt and have to type
# type 'exit' to get back to your bash prompt
# e.g. AVOID THIS IN NON-INTERACTIVE SCRIPTS!!!
sftp -rpC -P <port> "<user>@<host_ip>:<SRC_PATH>"
Connected to <host_ip>.
Changing to: <SRC_PATH>
sftp>
sftp> exit
# Download a folder and all of its contents,
# to name and path in "<DST_PATH>"
# note that any symlinks will copy only the symlink itself
# and NOT the data the link references
sftp -rpC -P <port> "<user>@<host_ip>:<SRC_PATH>" "<DST_PATH>"
2. Local push (e.g. from local terminal, upload files from local to remote)
Firstly, if you just try to reverse the parameters, like what my original answer had, then you will get a connection error. Why doesn't sftp make the upload syntax consistent with the download syntax? Your guess is as good as mine... I for one would have been a huge fan of that approach. But if you try it, here's what happens (note: this output is from 2 machines running Fedora 35 with correctly configured ssh where scp and rsync ... -e ssh work just fine and do not prompt for authentication).
# single file
sftp -pC -P <port> test.txt "<user>@<host_ip>:<DST_PATH>"
ssh: Could not resolve hostname test.txt: Name or service not known
Connection closed.
Connection closed
# dir
sftp -rpC -P <port> "<SRC_PATH>" "<user>@<host_ip>:<DST_PATH>"
ssh: Could not resolve <SRC_PATH>: Name or service not known
Connection closed.
Connection closed
Per the answer I linked to above, the correct way to do this is instead as follows
# push a single file from local to remote
sftp -pC -P <port> "<user>@<host_ip>:<DST_PATH>" <<< 'put test.txt'
# or
echo 'put test.txt' | sftp -pC -P <port> "<user>@<host_ip>:<DST_PATH>"
# push a entire dir (and its contents) from local to remote
# notice the inner single quotes to escape <SRC_PATH>
# for enclosing paths containing whitespace
sftp -rpC -P <port> "<user>@<host_ip>:<DST_PATH>" <<< "put '<SRC_PATH>'"
# or
echo "put '<SRC_PATH>'" | sftp -rpC -P <port> "<user>@<host_ip>:<DST_PATH>"
# or
printf 'put "%s" "%s"\n' "<SRC_PATH>" "<DST_PATH>" | \
sftp -rpC -P <port> "<user>@<host_ip>"
I found in my scripting that using a similar syntax for downloads, e.g.
# pull a entire dir (and its contents) from remote to local
# notice the inner single quotes to escape <SRC_PATH>
# for enclosing paths containing whitespace
printf 'get "%s" "%s"\n' "<SRC_PATH>" "<DST_PATH>" | \
sftp -rpC -P <port> "<user>@<host_ip>"
was less confusing but all of the above should work.
To copy multiple paths at once, an array works (or you could create a batch file listing each put command on a separate line and pass that to sftp using the -b <batchfile> option).
# copy multiple paths from array
arrPaths=("<SRC_PATH_1>" "<SRC_PATH_2>" "<SRC_PATH_3>");
printf 'put %s\n' "${arrPaths[@]}" | sftp -rpC -P <port> "<user>@<host_ip>:<DST_PATH>"
2022-Oct-10 Update: After running into some issues with rsync copies that contained spaces, I have updated the commands to use the -s option (explained in this answer)
However, one observation I have noticed where rsync differs from scp and sftp (in regards to handling spaces) is that scp was always fine with paths that contained inner quotes such as
scp -rp "remoteuser@remotehost:'/tmp/rsync-test/stuff from server/the data.txt'" "."
Whereas, if you do that in rsync, you'll get an error:
$ rsync -saXULz --progress -e ssh \
"remoteuser@remotehost:'/tmp/rsync-test/stuff from server/the data.txt'" "."
receiving incremental file list
rsync: [sender] change_dir "/home/remoteuser/'/tmp/rsync-test/stuff from server" failed: No such file or directory (2)
rsync error: some files/attrs were not transferred (see previous errors) (code 23) at main.c(1839) [Receiver=3.2.5]
rsync: [Receiver] write error: Broken pipe (32)
The fix for this is quite easy but maybe not intuitive if you are using to using the inner quoted path syntax from scp like I was: just use -s and get rid of the inner quotes. rsync is smart enough to handle it and it just works.
So the above command that had an error, would just be changed to:
$ rsync -saXULz --progress -e ssh \
"remoteuser@remotehost:/tmp/rsync-test/stuff from server/the data.txt" "."
And all should be good (assuming scp works fine for the same path).
| ssh working on all devices but scp from some devices gives "Connection closed" error |
1,635,063,773,000 |
man ssh says:
SSH_ASKPASS
If ssh needs a passphrase, it will read the passphrase from the
current terminal if it was run from a terminal. If ssh does not
have a terminal associated with it but DISPLAY and SSH_ASKPASS
are set, it will execute the program specified by SSH_ASKPASS
and open an X11 window to read the passphrase.
I'd like SSH to use an askpass program even if it was run from a terminal.
On occasion, I have to connect to servers, where there's some delay in showing a password prompt (maybe due to network issues, maybe due to attempted reverse DNS lookups, …). I get annoyed and switch to something else, and forget about the attempted connection. (Insert joke about attention span of a goldfish.) When I finally get back to it, the prompt's timed out and even a correct password would just result in a closed connection.
Keys would be one solution, but not every system I use has my usual SSH keys. However, I usually use Ubuntu systems, and Ubuntu has an SSH askpass program installed by default.
If an askpass window popped up, however, I'd be immediately aware of it. That's a good enough compromise for me, if only I can get it to work.
|
This will be a bit more complicated, but combination of several pieces will make it working:
Explanation
To force ssh to use $SSH_ASKPASS program, you can't allow ssh to see the real tty. It is just condition. This can be done by using setsid and using -n switch to ssh.
This case would initiate connection, but you would not be able to interact with the shell, which is probably also your requirement ;) (and also breaks your local TTY).
But you can give up the "first session". You should also add -N switch, which will suppress the remote command and will do just the authentication.
Also the possible output "junk" can be redirected to &> /dev/null if you are not interested in it.
Set up ControlMaster in ssh_config. It is cool feature and once the connection is established, you can "fire up" sessions pretty fast. This snippet in ~/.ssh/config should do that:
ControlPath ~/.ssh/controlmasters/%r@%h:%p
ControlMaster auto
ControlPersist 5m
You can add that into some host block listing your "slow candidates", or just everywhere. It is almost no overhead.
Final line
Then you should be able to connect in this way to the host you expect it will take a while:
setsid ssh -nN host
# wait, insert password in the X11 prompt
ssh host
# will bring you directly to your session
Whole process might be simplified by alias or bash function doing both in one step, but it is left on readers imagination.
Only command-line arguments
You can join both things together on command-line without ssh_config part:
setsid ssh -nNMS ~/.ssh/masters/%C host
# wait, insert password in the X11 prompt
ssh -S ~/.ssh/masters/%C host
# will bring you directly to your session
The following function should work when SSH options aren't specified:
ssh() {
if ! command ssh -o PasswordAuthentication=no "$1" true
then
setsid -w ssh -fnN "$1"
fi
command ssh "$@"
}
-f instructs SSH to go to the background just before program execution, which is after it has got the password.
-w tells setsid to wait for the program to end. In this case, that happens when SSH goes to the background. Combined with ssh -f, the manual wait between the two SSH commands can be eliminated.
The function assumes the first argument is the hostname.
The test is just to prevent unnecessary SSH connections.
| Can I get SSH to use an askpass program even if it was run from a terminal? |
1,635,063,773,000 |
The RFC:
Uniform Resource Identifier (URI) Scheme for Secure File Transfer
Protocol (SFTP) and Secure Shell (SSH)
presents the SSH URI as:
ssh://[<user>[;fingerprint=<host-key fingerprint>]@]<host>[:<port>]
Are there any known reasons why the OpenSSH ssh command doesn't follow this standard with the hostname option? It does not accept a port after a colon.
Example of a URI I was expecting to work:
$ ssh user@host:2222
ssh: Could not resolve hostname host:2222: Name or service not known
|
ssh predates the more general URI format (1998) by several years (1995 IIRC).
| Why doesn't the ssh command follow RFC on URI? |
1,635,063,773,000 |
In Ubuntu GNU/Linux 12.04, I have a user johndoe that is part of an sftponly group, set up to sftp to a chroot jail using
Subsystem sftp internal-sftp
Match Group sftponly
ChrootDirectory %h
ForceCommand internal-sftp
AllowTcpForwarding no
at the end of /etc/ssh/ssh_config. All components of the user's home directory are root-owned directories that are not writeable by any other user or group, as explained in man sshd_config (under ChrootDirectory). Inside his chroot jail, there is a writeable directory files:
sudo groupadd sftponly
sudo mkdir -p /home/sftponly/johndoe/files
sudo useradd -d /home/sftponly/johndoe -g sftponly -s /usr/sbin/nologin johndoe
sudo chmod go-w /home/sftponly/{,johndoe}
sudo chown johndoe:sftponly /home/sftponly/johndoe/files
sudo chmod ug+rwX /home/sftponly/johndoe/files
(Setting the shell to /bin/false did not work with either ssh or sftp. With nologin as the shell ssh connects, shows "MOTD", and then disconnects, which is the expected behavior.)
But sftp fails with the message Received message too long 1416128883. I know this failure is caused by "MOTD" (Message Of The Day), as sftp expects a "clean login." I have tried disabling all "MOTD" pieces on the server using the following, with (these results):
Adding PrintLastLog no and PrintMotd no to the end of /etc/ssh/ssh_config and restarting ssh using restart ssh. (No effect. Testing with ssh shows both "MOTD" and "Last Login:".)
Commenting out session optional pam_motd.so in /etc/pam.d/sshd. (Prevents MOTD. But there is no corresponding entry for "LastLog" so, testing with ssh, "Last Login:" still shows up and hence sftp still fails.)
Commenting out session optional pam_lastlog.so and session optional pam_motd.so in /etc/pam.d/login. (No effect. Testing with ssh shows both MOTD and "Last Login:".)
Creating the .hushlogin file on the client using touch ~/.hushlogin. (No effect.)
I am out of ideas. Where else may this "Last Login:" message be coming from and how can it be disabled (ideally only for sftp and not for ssh logins, but, I imagine as sftp uses ssh, the message is going to be there either for both or none)?
|
A typo on my part was the cause of the unreasonable behavior I was experiencing above. It is /etc/ssh/sshd_config (corresponding to the ssh daemon) that must be edited, not /etc/ssh/ssh_config (corresponding to the ssh client). I leave this question here in case it may help someone else.
| How to prevent "Last Login:" message from showing up when using sftp? |
1,635,063,773,000 |
I'm running an ubuntu image in a docker container, with my .ssh directory mounted from my native MacOs environment.
My .ssh/config file contains
Host *
AddKeysToAgent yes
UseKeychain yes
IdentityFile ~/.ssh/id_ed25519_common
This works fine on a mac, but AddKeysToAgent and UseKeychain are not valid for linux, and anything (e.g. git) that uses the openssh-client package won't just ignore the unrecognised directives, but fail and exit.
Is there any way of having a .ssh/config file that will let me share it across mac and linux?
|
You can use the Match keyword in the ssh config file to restrict a portion of the configuration to only apply under certain conditions. For the excerpt in the question, something like the following should work:
Host *
AddKeysToAgent yes
IdentityFile ~/.ssh/id_ed25519_common
Match exec "uname -s | grep Darwin"
UseKeychain yes
On a linux system, the grep will return failure (1), and so the following line(s) will be ignored; on the Mac host, the grep will return success (0) and the UseKeychain yes line will be applied.
The Match block is terminated by the next Match, Host, or end of file.
Note that AddKeysToAgent is not platform-specific, but is available in OpenSSH since version 7.2, so presumably you are using an older version of OpenSSH in the Ubuntu container but not on the Mac host.
| Can I ignore errors in my ssh config? |
1,635,063,773,000 |
A vulnerability scan showed that in a Debian 10 system, insecure MAC algorithms are in use: [email protected],[email protected],[email protected],hmac-sha1
When I do ssh -Q mac, I get the following results:
hmac-sha1
hmac-sha1-96
hmac-sha2-256
hmac-sha2-512
hmac-md5
hmac-md5-96
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
In the /etc/ssh/ssh_config file there is line that's commented out:
# MACs hmac-md5,hmac-sha1,[email protected]
There is no mention of umac-64-etm or hmac-sha1-etm in the file. In /etc/ssh/sshd_config there is no MAC keyword at all. How can I disable these weak HMACs?
|
The list of supported MAC algorithms is determined by the MACs option, both in ssh_config and in sshd_config. If it's absent, the default is used. If you want to change the value from the default, either edit the existing entry or add one if it isn't present. For example:
MACs hmac-sha2-256,hmac-sha2-512,[email protected],[email protected],[email protected]
Recent enough versions of OpenSSH (and Debian 10 is recent enough) also allow a differential specification, for example to disable all short MACs and MACs based on MD5 or SHA-1:
MACs -*md5*,*sha1,*sha1-*,*-64,*-96
Note that none of the default algorithms are actually insecure. A 64-bit MAC would be very weak for offline use, but it's acceptable for network messages which are only valid within one connection which would time out before anyone can break even a 64-bit MAC. (It's a sign that they're still in the default list for OpenSSH, even though OpenSSH is very proactive about security.) MD5 and SHA1 have weaknesses that make them insecure as hashes, but the HMAC construction doesn't care about these weaknesses. I would recommend keeping at least hmac-sha1 for interoperability with older systems unless you absolutely need to disable it for compliance (this would be about compliance and not about security).
| How to disable weak HMAC Algorithms? Not found in ssh_config or sshd_config file |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.