date int64 1,220B 1,719B | question_description stringlengths 28 29.9k | accepted_answer stringlengths 12 26.4k | question_title stringlengths 14 159 |
|---|---|---|---|
1,415,183,595,000 |
Currently playing around with the dialog command and I have noticed that when I press Shift-Tab or press ESC, the execution immediately exits and I am back on the command prompt. Since this is not a signal, I can't trap and discard it, so how would I "trap"/capture this escape and discard it so that the only way to exit the dialog is through whatever widget/box I set up?
Note: I have already researched why the combination of Shift and Tab triggers the escape. It is not a single keystroke and the solutions I have found only work when the input expected is a single keyboard stroke. Dialog does not have documentation on this topic and anything outside of its man page seems to be lacking.
|
Shift+Tab is usually a back-tab on terminals that you are likely to use.
The manual page section KEY BINDINGS comments that dialog's key bindings can be curses keys
It may be any of the names derived from curses.h, e.g., "HELP" from
"KEY_HELP".
and in the section Built-in Bindings explains that the --trace option can be used to show the built-in bindings:
This manual page does not list the key bindings for each widget, because that detailed information can be obtained by running dialog. If
you have set the --trace option, dialog writes the key-binding information for each widget as it is registered.
As an example, it shows how to bind TAB and BTAB (the name derived from curses KEY_BTAB):
bindkey formfield TAB form_NEXT
bindkey formbox TAB form_NEXT
bindkey formfield BTAB form_prev
bindkey formbox BTAB form_prev
KEY_BTAB (see getch manual page) is the back-tab key.
In terminfo, that is named kcbt:
key_btab kcbt kB back-tab key
You can see a terminal description using infocmp.
If you happen to have set TERM to a terminal description which does not define kcbt, then (because it is usually an escape sequence), curses will not recognize it, and will pass the individual bytes to the application (dialog). dialog uses the ASCII escape character (ESC) to cancel the current widget. A shell script can check for this by inspecting the exit-status. The ENVIRONMENT section documents environment variables which can be used to customize the exit-status:
Define any of these variables to change the exit code on
Cancel (1), error (-1), ESC (255), Extra (3), Help (2),
Help with --item-help (2), or OK (0). Normally shell
scripts cannot distinguish between -1 and 255.
| How to capture/ignore ESC during the execution of dialog? |
1,415,183,595,000 |
Is it possible for a2ps to interpret the ANSI escape codes ?
$ echo -e "\033[31mHello\e[0m World" | ./bin/a2ps -o output.ps
if not, do you know another tool that would do this task ?
|
aha - Ansi HTML Adapter
Converts ANSI escape sequences of a unix terminal to HTML code.
aha Git repo
Then you just need a tool to make HTML to PS like html2ps.
| printing ansi colors/escape codes with a2ps |
1,415,183,595,000 |
I'm able to get the desired output by running this command on terminal:
top -bn 1 | grep "^ " | awk '{ printf("%-8s %-8s %-8s %-8s %-8s %-8s %-8s\n", $1, $2, $9, $10, $6, $11, $12); }' | head -n 6
And I'm able to SSH twice and get the hostname by running this on terminal:
ssh 192.168.5.209 "ssh 192.168.5.210 exec \"hostname\""
The 209 is serving as something like a portal so I can only SSH from 209 to 210. But the problem is how do I replace the "hostname" with the top command that I write above? There are too much special characters.
I am writing a script to execute from PHP btw.
|
grep, awk, and head can be merged and run locally
ssh 192.168.5.209 "ssh 192.168.5.210 top -bn 1 " |
awk '/^ / { printf("%-8s %-8s %-8s %-8s %-8s %-8s %-8s\n", $1, $2, $9, $10, $6, $11, $12); c++ ; if (c==6) exit ;}
where
/^ / search for line starting with a space
c++ ; if (c==6) exit ; will exit awk after 6 line printed.
| SSH twice and run command, escaping character? |
1,415,183,595,000 |
I want to delete anything that follows a % to the end of the line. Using
cat /tmp/foo.txt | sed 's/%.*$//'
works great with one exception: I want to ignore any escaped percent signs \%. So with the following file saved as /tmp/foo.txt
abcd %123
xyz \%xyz
xyz \%xyz %123
the output I want is
abcd
xyz \%xyz
xyz \%xyz
What is the appropriate regular exception handling to do this?
|
You need to look at the character before the percent.
sed 's/\([^\\]\)%.*/\1/'
If the previous character is not a backslash, keep that char and remove the rest.
This answer assumes that the % does not appear at the beginning of the line. If it does, then we need to check for it
sed 's/\(^\|[^\\]\)%.*/\1/'
| sed exception handling of escaped characters |
1,415,183,595,000 |
I have a JSON file that looks like:
{
...
"python.pythonPath": "",
"python.defaultInterpreterPath": "",
...
}
I want to update it to
{
...
"python.pythonPath": "/Users/user/.local/share/virtualenvs/venv-Qxxxxxx9/bin/python",
"python.defaultInterpreterPath": "/Users/user/.local/share/virtualenvs/venv-Qxxxxxx9/bin/python",
...
}
I am confused about using escape characters / and single and double quotation marks. How do I do this using sed?
FYI. I am using macOS
I tried :
sed -i "" 's|/"/"|/"/Users/user//.local/share/virtualenvs/venv-Qxxxxxx9/bin/python/"' settings.json
|
I was not able to get the sed command working. I however found a way to run a Python script inside bash that did the job for me.
If anyone is interested:
export new_path="/Users/user/.local/share/virtualenvs/venv-Qxxxxx9/bin/python"
python3 - << EOF
import json
import os
with open('settings.json', mode='r+') as file:
data = json.load(file)
data['python.defaultInterpreterPath'] = os.environ['new_path']
data['python.pythonPath'] = os.environ['new_path']
file.seek(0)
json.dump(data, file, indent=4, sort_keys=True)
file.truncate()
EOF
echo 'continue bash'
| Use "sed" to replace file containing "" and \ |
1,415,183,595,000 |
I use the kitty terminal emulator for my day to day development, and I learned that it has these custom escape sequences for fancy underlines. I really wanted to get them working in vim, and after some vimrc tweaks, they started showing up. However, whenever I'm in a tmux session, the codes suddenly stop working. I've read a bit into this and it looks like tmux is 'swallowing' the escape codes, and someone suggested surrounding the sequences like so: "\ePtmux;\e<foo>\e\\, but no luck: no underline/undercurl was showing.
This could be something impossible to do, but I have no idea where to start looking if it isn't, so any help would be appreciated!
My .tmux.conf
set -g default-terminal "xterm-kitty"
set -sg escape-time 0
|
tmux is a terminal emulator. The control sequences that kitty understands are irrelevant to applications that are talking to a tmux terminal. tmux does not understand them. Your applications running under tmux have no direct connection to a kitty-emulated terminal.
For such a thing to work, the terminal emulator part of tmux has to understand these control sequences coming to it from applications, the internals of tmux have to understand the concept of different sorts of underlines, and the part of tmux that realizes its display onto another terminal needs to understand both the requisite control sequences and what terminal types support them. That latter in particular also requires extending the terminfo database with more capability definitions.
None of this has been done. Or even suggested.
If you want this, write the code and submit patches to tmux, terminfo, and other related projects that will need updating; or employ someone else to do so.
| Using extended escape codes in tmux |
1,415,183,595,000 |
I have a shell script I am trying to get working. I need the output to be a certain way and I know I'm just not escaping the characters correctly.
script:
#!/bin/bash
set -x
DATE=$(date +%Y-%m-%d-%M)
ELEMENTS="ele1,ele2,ele3"
TOPIC="dogs cats"
FILE="./$DATE.csv"
COMMAND="python /home/script.py"
$COMMAND $ELEMENTS "$TOPIC" | tee -a $FILE
What happens from set in the terminal when I run it is:
++ date +%Y-%m-%d-%M
+ DATE=2016-02-01-21
+ ELEMENTS=a list of elements
+ TOPIC='dogs cats'
+ FILE=./2016-02-01-21.csv
+ COMMAND='python /home/script.py'
+ python /home/script.py ele1,ele2,ele3 'dogs cats'
+ tee -a ./2016-02-01-21.csv
What I need it to be is "dogs cats" vs 'dogs cats'. The python command requires double quotes for multi word strings.
This is wheezy running on a raspberry pi.
|
Change
TOPIC="dogs cats"
to
TOPIC='"dogs cats"'
to have " embedded inside the variable.
| Double quotes issue in bash script |
1,415,183,595,000 |
When I use
cat Variables/user-extensions.js | sed -e 's/css/XXX/'
on an input file of the form
storedVars["css_body"] = "css=body";
storedVars["css_main"] = "css=main";
I see output such as
storedVars["XXX_body"] = "css=body";
storedVars["XXX_main"] = "css=main";
However if I add > x and then use vi to edit the x file I see
storedVars^[[31m[^[[m^[[31m"XXX_body"^[[m^[[31m]^[[m ^[[31m=^[[m ^[[31m"css=body"^[[m^[[31m;^[[m
storedVars^[[31m[^[[m^[[31m"XXX_main"^[[m^[[31m]^[[m ^[[31m=^[[m ^[[31m"css=main"^[[m^[[31m;^[[m
instead of
storedVars["XXX_body"] = "css=body";
storedVars["XXX_main"] = "css=main";
which is what I get if I let the output go to standard output, or if I only cat the output file and don't edit it with vi. I can cat the file and pipe to head or tail and the output is normal, no extra characters.
If I vi the source .js file I do not see these extra characters.
|
The problem is in using my aliased cat which adds the special characters.
Instead of
cat Variables/user-extensions.js | sed -e 's/css/XXX/' > x
use
sed 's/css/XXX/' Variables/user-extensions.js > x
| Why is vi (but not cat) showing ^[[31m[^[[m^[[31m" after I use sed and output to a file I then edit? [closed] |
1,415,183,595,000 |
I am trying to assign the result of a sed command to a variable in bash, but I am unable to escape everything corrrectly (probably just due to my lack of knowledge in bash), I have tried:
hash_in_podfile=$( sed -rn 's/^ *pod [\'\"]XXX["\'],.*:commit *=> *["\']([^\'"]*)["\'].*$/\1/p' ${PODS_PODFILE_DIR_PATH}/Podfile )
but I am getting
bash_playground.sh: line 9: unexpected EOF while looking for matching
`''
UPDATED SCRIPT
This is the script I am using updated with the code from the answer. Only the path and the comment have changed:
#!\bin\sh
PODS_PODFILE_DIR_PATH='/Users/path/to/file'
# just a comment
hash_in_podfile=$(sed -rnf - <<\! -- "${PODS_PODFILE_DIR_PATH}/Podfile"
s/^ *pod ['"]XXX["'],.*:commit *=> *["']([^'"]*)["'].*$/\1/p
!
)
echo $hash_in_podfile
executed with sh script_name.sh
sh --version yields:
GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin20)
Copyright (C) 2007 Free Software Foundation, Inc.
On execution I get:
script_name.sh: line 6: unexpected EOF while looking for matching `"'
script_name.sh: line 10: syntax error: unexpected end of file
|
There are two issues in your script:
The sh on macOS is a very old version of the bash shell, and it has a bug that stops you from using unbalanced quotes in here-documents in command substitutions:
$ a=$( cat <<'END'
> "
> END
> )
> sh: unexpected EOF while looking for matching `"'
(I had to press Ctrl+D after the ) at the end there.)
You can get by this by installing a newer bash shell from the Homebrew package manager (or equivalent), or by using the zsh shell on macOS.
The sed on macOS does not have an -r option. To use extended regular expressions with sed on macOS, use -E (this is also supported by GNU sed nowadays). Your expression does not use extended regular expression features though, so just removing the option would be ok too. macOS sed also can't use - as the option-argument to -f to mean "read from standard input". Use /dev/stdin instead.
Suggestion:
#!/bin/zsh
PODS_PODFILE_DIR_PATH='/Users/path/to/file'
# just a comment
hash_in_podfile=$(sed -n -f /dev/stdin -- $PODS_PODFILE_DIR_PATH/Podfile <<'END'
s/^ *pod ['"]XXX["'],.*:commit *=> *["']([^'"]*)["'].*$/\1/p
END
)
echo $hash_in_podfile
If all you want to do is to output the value, then don't use an intermediate variable:
#!/bin/zsh
PODS_PODFILE_DIR_PATH='/Users/path/to/file'
# just a comment
sed -n -f /dev/stdin -- $PODS_PODFILE_DIR_PATH/Podfile <<'END'
s/^ *pod ['"]XXX["'],.*:commit *=> *["']([^'"]*)["'].*$/\1/p
END
| Assign sed command correctly |
1,415,183,595,000 |
I suspect the following has been answered already but I don't know the terminology for the issue I'm having well enough to find an existing answer.
I'm working on a command to go through a list of files and output on each line the filename followed by the count of lines that start with P. I've gotten this far:
find -type f | xargs -I % sh -c '{ echo %; grep -P "^P \d+" % | wc -l; } | tr "\n" ","; echo ""; '
(The actual find command is a bit more involved but short story is it finds about 11k files of interest in the directory tree below where I'm running this)
This command is about 98% working for my purposes, but I discovered there is a small subset of files with parentheses in their names and I can't ignore them or permanently replace the parentheses with something else.
As a result I'm getting some cases like this:
sh: -c: line 0: syntax error near unexpected token `('
I know parentheses are a shell special character so for example if I was running grep directly on a single file with parentheses in the name I'd have to enclose the filename in single quotes or escape the parentheses. I tried swapping the quote types in my command (doubles outermost, singles inner) so I could put the '%' in the grep call in single quotes but that didn't help.
Is there a way to handle parentheses in the find -> xargs -> sh chain so they get handled correctly in the sh call?
|
Better not embed data (filenames) directly in code (the shell scriptlet). Instead pass the filename as an argument to the shell you have xargs run:
find -type f | xargs -I % \
sh -c '{ echo "$1"; grep -c -P "^P \d+" "$1"; } | tr "\n" ","; echo' sh %
Also you should be able to use grep -c instead of grep | wc -l, it at least makes the command a bit shorter.
| Handle parentheses in this xargs multi-command |
1,415,183,595,000 |
I have a string that is a path:
/tmp/something
I need to escape the forward slashes with backslashes:
\/tmp\/something
How can I do this? Maybe sed?
Please point me in the right direction.
|
You can do it with Bash's own variable manipulation methods (parameter expansion), though the syntax is fairly monstrous:
$ string='/tmp/something'
$ escapedstring="${string//\//\\\/}"
$ printf '%s\n' "$escapedstring"
\/tmp\/something
To explain this further, in bash ${var//xxx/yyy} means "take variable var and replace all occurrences of xxx with yyy." In this case, you need to escape the slashes in specifying the substituend and substitute; the former is \/ for a single forward slash and latter is \\\/ for a backslash plus forward slash, so you end up with the ridiculous looking ${string//\//\\\/}.
Remember not to use echo to display its contents as depending on the implementation or environment, echo may do it's own processing of backslash characters.
| bash insert backslash for every slash in string |
1,415,183,595,000 |
Let's say I want to search a file for a string that begins with a dash, say "-something":
grep "-something" filename.txt
This throws an error, however, because grep and other executables, as well as built-ins, all want to treat this as a command-line switch that they don't recognize. Is there a way to prevent this from happening?
|
For grep use -e to mark regex patterns:
grep -e "-something" filename.txt
For general built-ins use --, in many utilities it marks "end of options" (but not in GNU grep).
| Stop executables and built-ins from interpreting a string argument starting with - as a switch? [duplicate] |
1,415,183,595,000 |
It took me 10 hours of searching the net, and testing techniques to get the results that worked on any shell (#!/bin/sh).
In BASH this is relatively simple, because read can be told how many characters are to be grabbed, and if a delimiter is found it will not wait to exit.
stty -icanon -echo; echo -en "\033[6n"; read -d R -n 12 ESCPOS; stty "$x_TERM"; \
ESCPOS=`echo "$ESCPOS" | tail -c +3`; echo "$ESCPOS"
How to write a sh script version, compatible with any shell?
|
Note:
unlike the wrongly copied and continually upvoted answer provided
(points scoring?), the following script IS NON-BLOCKING, and does
not care what length returned input may be. IE it will work with
ANY screen size.
With SH it is more complex, and I was unable to find enhanced command line version of the built-in read, eventually I found a mention of dd on STDIN, here is the result. NOTE that the SH version of built-in echo does not permit the use echo -en although /bin/echo -en does work we use printf instead.
#!/bin/sh
x_TERM=`stty -g`
stty -icanon -echo
printf "\033[6n"
ESCPOS=""
X=""
I=0
while [ ! "$X" = "R" ]; do
X=`dd bs=1 count=1 2>/dev/null`
I=`expr $I + 1`
if [ $I -gt 2 -a ! "$X" = "R" ]; then
ESCPOS="$ESCPOS$X"
fi
done
stty "$x_TERM"
#echo "$ESCPOS"
CSRLIN=`echo "$ESCPOS" | cut -d \; -s -f 1`
POS=`echo "$ESCPOS" | cut -d \; -s -f 2`
echo "$CSRLIN"
#exit 0 <= dont use inline
I used the same code in two differnt scripts, one outputs CSRLIN, the other POS.
EDIT: you need to inline this script to use it in another script (eg . CSRLIN, as the shell has to be in interactive mode.
Cheers
Paul
| How to get the results from "\033[6n" in an sh script |
1,415,183,595,000 |
I have a shell script part of which is the following JSON:
curl --request POST \
--url 'https://'$jira_instance'.atlassian.net/rest/api/2/field/'$field_ID'/context/'$context_ID'/option' \
--user $jira_user'@whatever.com:'$api_token \
--header 'Accept: application/json' \
--header 'Content-Type: application/json' \
--data '{
"options": [
{
"disabled": false,
"value": "'$1'"
}
]
}'
This only works if $1 contains no spaces.
If $1 contains any space(s) then I get the following error that tells me cURL is breaking:
curl: (3) unmatched close brace/bracket in URL position 11:
I have also tried with double quotes inside double quotes (""$1"") but this doesn't do anything at all.
Kindly advise.
|
Generally, to properly quote a variable within single quotes in Bash, use '"$var"' (single quote followed by double quote). The
first single quote ends the single-quoted string, then there's the double-quoted variable, and the second single quote restarts the single-quoted string.
Without the double-quotes, the parameter expansion is subject to word splitting, and spaces will split the text into multiple arguments to curl, causing it to treat the second one as a URL to fetch.
Given your example, this is how you should do it:
"value": "'"$1"'"
The extra quotes are removed by Bash, so if $1 is, say, one two, the final output would look like the following:
"value": "one two"
(Note that the variable value can't contain double quotes or they must be properly escaped.)
| Issue with double quotes inside double quotes in JSON |
1,415,183,595,000 |
I am trying to echo I say "Hello, World!" with bash -c. This is (some of) what I have tried:
$ bash -c "echo I say \"Hello, World"'!'"\""
$ bash -c "echo I say "'"'"Hello, World"'!'"\""
$ bash -c "echo I say """Hello, World"""'!'
$ bash -c $'echo I say \"Hello, World!\"'
$ bash -c 'echo I say "Hello, World!"'
They all print
I say Hello, World!
How can I show the quotes ?
|
The problem lies in the fact that you have nested quotes, which makes quoting somewhat involved. Since you don't have a "comprehensive" quote around your arguments to echo, all your attempts (except for your 3rd attempt(1)) are actually passing three arguments to echo, which are all subject to quote removal:
I
say
Hello, World!
The key point is that upon interpretation of the "outer" command, the outer quotes of the argument to bash -c are removed. The inner quotes remain, either because they are escaped or because they are of different type than the outer ones.
Then, when the bash instance you explicitly called processes that argument (the "inner" command), it itself performs quote-removal when interpreting the arguments to the echo call. Thus, the quotes you put around Hello, World! will ensure that this is considered one argument to echo, but be removed in the same process (and thereby lost to echo).
Since you don't need variable expansion in the ("inner") echo command, I would go with the single-quote syntax as follows:
bash -c 'echo "I say \"Hello, World\"!"'
That way you are passing one single argument to echo, and the quote-escaping inside the double-quotes will work as expected.
(1) In the 3rd attempt you show, you are actually passing 2 arguments to bash -c:
echo I say Hello, and
World!
leading to four arguments to echo seen by the "inner" command. This is because your attempt to "interrupt" the outer double-quotes with """ doesn't work that way - instead, the first of these double-quotes mean that the starting double-quote of the bash -c argument is closed after the space. This is then seen as being followed by an empty double-quoted string, and then by an unquoted Hello,. All these are concatenated because there is no space in between them.
Then, since the space following is unprotected, the outer bash will now consider the remainder a second argument, starting with the (again unquoted) World, a double-quoted empty string, and then an opened-but-unclosed double-quoted string containing '!'. The fact that it is not correctly closed is masked by the error message you should receive about an "event not found", since the starting double-quote makes the following single-quote merely a character to-be-printed, whereby the ! is no longer protected from interpretation as history reference.
| Show quotes with echo inside bash -c |
1,596,129,203,000 |
This feels like an incredibly simple task, but I can't get it to work. I want to put the first 13 files in a directory into a .zip archive. The obvious way to do this is
zip first13.zip $(ls | head -n 13)
But this fails because some of the filenames--which I can't change for stupid institutional reasons--have spaces in them. Replacing ls with ls --quoting-style=shell-always doesn't help (it actually makes things worse, because somehow zip ends up looking for files that start and end with literal ' characters, and yet still parses the spaces...) and neither does
ls | head -n 13 | xargs zip first13.zip
Again, zip parses the spaces.
Weirdly, zip all.zip ./* works fine, so clearly some kind of escaping is possible, but I don't know how to replicate whatever zsh does in its globbing.
In case there is more than one version of zip out there, mine is the one that comes in Arch Linux's official zip package, and identifies itself as Copyright (c) 1990-2008 Info-ZIP. The shell is zsh version 5.8.
|
Since you are using zsh, you should be able to use a glob qualifier of the form [m,n] to select a range of matches - avoiding the head pipeline (and its implicit whitespace splitting) altogether:
zip first13.zip ./*([1,13])
See man zshexpn for further details
| How do I pass filenames with spaces in them to `zip`? |
1,596,129,203,000 |
I am using \0n escape sequence with echo -e and printf where n is the octal value of the ASCII character to be printed. When i used the statement echo -e "\0101" the shell is printing character A but when i use printf "\0101" the shell is printing 1 which is the Least significant bit of the octal number i provided but if i remove 0 in the starting and use the command as printf "\101" it is correctly printing A as expected. so my doubt is why there is such a difference for this particular escape sequence, i tried for many other escape sequences but they gave same results with both echo and printf.I am using Ubuntu and currently working on bash.
|
From man echo1:
\0NNN byte with octal value NNN (1 to 3 digits)
From man printf1:
\NNN byte with octal value NNN (1 to 3 digits)
The two commands are not accepting the same format for octal sequences.
You can easily check that their actual output is quite different:
$ echo -en "\0101" | od -A n -t o1
101
echo is actually printing the intended single character A.
$ printf "\0101" | od -A n -t o1
010 061
printf, on the other hand, is seeing \010 as a character escape sequence and the subsequent 1 as a literal character, which is just copied to the output.
It is thus printing a <backspace> (which has no visible effect, being the first character of the string), whose octal representation is 010, followed by the non-interpreted 1.
1 To be precise, the commands you are running are most likely the Bash builtin ones, not those described by man (likely from coreutils). But both help echo and help printf confirm the man's syntax or directly refer to it.
| printf and echo -e are giving different results |
1,596,129,203,000 |
I am trying to understand what the second echo statement does exactly (it's an existing script)..
echo "Triggering report.. "
curl -s -X POST "http://aaa.bbb"
echo -e \ '\
'
I read that -e enables backslash escaping. However, not sure why there is one backslash outside, and also why there is a backslash alone inside the quote instead of \n
|
That second echo is equivalent to the following more portable command:
printf ' \\\n\n'
This outputs a space, a backslash, and two literal newline characters.
As a comparison, the echo command outputs these characters by outputting an escaped space together with a literal backslash and a literal newline character. The second newline character is added to the output by default by echo. The initial space needs to be escaped as it's not part of any quoted string (it would be removed by the shell splitting the command into words otherwise), and the backslash needs to be in a single quoted string since it otherwise would escape the next character.
The -e option used in the command does nothing here and could be dropped.
Equivalent formulations for echo (in bash):
echo -e ' \\\n'
echo ' \
'
echo -n -e ' \\\n\n'
echo -n ' \
'
See also:
Why is printf better than echo?
| I am trying to understand what a particular echo statement does |
1,596,129,203,000 |
I have a 'typescript' file that if i cat -v I get the following within the output:
M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-
These seem to be rendered ─ within the terminal while running the 'typescript'. How can I transform these to an appropriate plain text representation?
Running sed "s/M-bM-^TM-^@/testing123/g" on this file does not seem to work.
Here is the whole file:
cat -v typescript
Script started on 2018-07-07 19:08:54+00:00
^[[?1049h^[[22;0;0t^[[H^[[2J^[[?25l^[[1;1H^[(B^[[mHello, ^[[2;1H^[(B^[[mWorld! ^[[3;1H^[(B^[[mM-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@M-bM-^TM-^@^[[4;1H^[(B^[[m ^[[5;1H^[(B^[[m ^[[6;1H^[(B^[[m ^[[7;1H^[(B^[[m ^[[8;1H^[(B^[[m ^[[9;1H^[(B^[[m ^[[10;1H^[(B^[[m ^[[11;1H^[(B^[[m ^[[12;1H^[(B^[[m ^[[13;1H^[(B^[[m ^[[14;1H^[(B^[[m ^[[15;1H^[(B^[[m ^[[16;1H^[(B^[[m ^[[17;1H^[(B^[[m ^[[18;1H^[(B^[[m ^[[19;1H^[(B^[[m ^[[20;1H^[(B^[[m ^[[21;1H^[(B^[[m ^[[22;1H^[(B^[[m ^[[23;1H^[(B^[[m ^[[24;1H^[(B^[[m ^[[25;1H^[(B^[[m ^[[26;1H^[(B^[[m ^[[27;1H^[(B^[[m ^[[28;1H^[(B^[[m ^[[29;1H^[(B^[[m ^[[30;1H^[(B^[[m ^[[31;1H^[(B^[[m ^[[32;1H^[(B^[[m ^[[33;1H^[(B^[[m ^[[34;1H^[(B^[[m ^[[?1049l^[[23;0;0t^[[?12l^[[?25h^[(B^[[m^[[?12l^[[?25h5^M
zsh:1: command not found: k^M
Script done on 2018-07-07 19:08:55+00:00
|
Assuming that M- is meta and ^ is control, the sequence M-b M-^T M-^@ represents hex e4 94 80. The character ─ you gave is unicode U2500, "BOX DRAWINGS LIGHT HORIZONTAL". If you line up the bit patterns, you get something like
1110 0100 1001 0100 1000 0000 = e4 94 80
0 0100 1 0100 00 0000 = 2500
So this seems to be a multibyte encoding, where the MSBs denote "first byte" and "following byte", but it's not entirely clear how. (Or this guess is wrong, and in reality the encoding is different). This is not UTF-8, and I have no idea what it is.
I'm also not sure if this answers your question, because you already know that this sequence is rendered as a single character, and which character that is. And in the same way you know that, you'd be able to find out other characters.
So without any more information this probably has no real answer.
| What is this sequence of control characters (M-bM-^TM-^@) (dashes)? How can I transform these? [closed] |
1,596,129,203,000 |
I found that groff uses different ways to indicate bold text for the utf8 output format.
On FreeBSD 14, groff emits escape codes for a terminal (ESC, [1m):
$ printf ".Dd today\n.Sh NAME\n" | groff -mandoc -Tutf8 | od -c
0000000 \n 033 [ 1 m N A M E 033 [ 0 m \n
[...]
On Linux (debian Bookworm) is uses backspaces and overstriking:
$ printf ".Dd today\n.Sh NAME\n" | groff -mandoc -Tutf8 | od -c
[...]
0000120 N \b N A \b A M \b M E \b E \n
Why is it so and is there a way to make Linux groff also use ESC codes for the terminal? I have read the groff man page from top to bottom but can't find an option to change this behavior.
(I need to post-process the result and ESC codes make that much easier and flexible.)
EDIT: The solution (thanks go to @egmont) was to read Debian's grotty(1) manual and then force the SGR behavior with
printf ".Dd today\n.Sh NAME\n" | GROFF_SGR=y groff -mandoc -Tutf8
|
Debian Bookworm configures groff 1.22 for the old backspace-overwrite behavior you see there, and documents it in their patched grotty manual page along with how to revert to the newer SGR (\e[1m-like) behavior:
printf ".Dd today\n.Sh NAME\n" | GROFF_SGR=y groff -mandoc -Tutf8
It seems that the given configuration and patch is no longer there in their groff 1.23 package in unstable, as well as in Ubuntu 23.04. So it's probably the last Debian version you see with this old behavior, they're switching to the new SGR method, following upstream groff's defaults.
| groff -mandoc creating "ESC[1m" versus overstriking with backspace for bold text |
1,596,129,203,000 |
Is it possible to get dialog command, example:
dialog --title "HELLO" --yesno "Are you sure?" 6 30
into a file with all ANSI escape codes, so it can be printed later?
You can redirect the dialog into a file to get the output but you can't interact with the page, so it may be hard to exit.
|
You can use script:
script -q -c 'dialog --title "HELLO" --yesno "Are you sure?" 6 30'
dialog will run interactively, so you’ll be able to exit easily, and even track screen changes made in response to user input if you with (script supports timestamps, which can be useful here).
The output will be stored in a file named typescript; you can change that by specifying a file name on the command line. The file might contain start and end lines:
Script started on ...
Script done on ...
Remove those if necessary, and you’ll be left with dialog’s output, including escape codes.
| Saving ANSI codes from dialog command into a file |
1,596,129,203,000 |
I'm writing a bash script to find all the images in the folder and find if they have corrupt endings with ImageMagick.
This is the command I'm trying to automate:
identify -verbose *.jpg 2>&1 | grep "Corrupt" | egrep -o "([\`].*[\'])"
The issue I'm having is with storing the identify command into a variable.
There are multiple types of quotes that are present in the command I keep getting an error line 8: corrupt: command not found
#!/bin/bash
# This script will search for all images that are broken and put them into a text file
FILES="*.jpg"
for f in $FILES
do
corrupt = "identify -verbose \"$f\" 2>&1 | grep \"Corrupt\" | egrep -o \"([\`].*[\'])\""
if [ -z "$corrupt" ]
then
echo $corrupt
else
echo "not corrupt"
fi
done
Is there a way to escape that command correctly?
UPDATE:
Some progress:
#!/bin/bash
# This script will search for all images that are broken and put them into a text file
FILES="*.jpg"
for f in $FILES
do
echo "Processing $f"
corrupt="identify -verbose $f 2>&1 | grep \"Corrupt\" | egrep -o \"([\`].*[\'])\""
if [ -z "$corrupt" ]
then
echo $corrupt
else
echo "not corrupt"
fi
done
This no longer throws an error, but it looks like it just stores the variable as a string.
How can I run this command?
UPDATE: Some progress. Now the command is running:
#!/bin/bash
# This script will search for all images that are broken and put them into a text file
FILES="*.jpg"
for f in $FILES
do
echo "Processing $f"
corrupt=`identify -verbose $f | grep \"Corrupt\" | egrep -o \"([\`].*[\'])\"`
$corrupt
if [ -z "$corrupt" ]
then
echo $corrupt
else
echo "not corrupt"
fi
done
But the output of pipes is separate:
Processing sdfsd.jpg
identify-im6.q16: Premature end of JPEG file `sdfsd.jpg' @ warning/jpeg.c/JPEGWarningHandler/387.
identify-im6.q16: Corrupt JPEG data: premature end of data segment `sdfsd.jpg' @ warning/jpeg.c/JPEGWarningHandler/387.
I just need the final `sdfsd.jpg' string.
|
What you are probably looking for is a way of identifying corrupt images. It's easy to query the identify tool for its exit-status to see whether it managed to identify the image file or not.
#!/bin/sh
for name in *.jpg; do
if identify -regard-warnings -- "$name" >/dev/null 2>&1; then
printf 'Ok: %s\n' "$name"
else
printf 'Corrupt: %s\n' "$name"
fi
done
The above uses the exit-status of identify to determine whether the file was corrupt or not. The -regard-warnings option escalates the warnings you mention into errors turn, which makes them affect the exit-status of the utility.
You very seldom need to store actual globbing patterns in variables. You can often get a utility's success/failure status by testing its exit-status like what we show above without parsing the tool's output.
For older ImageMagick releases (I'm using 6.9.12.19), use convert instead of identify.
#!/bin/sh
for name in *.jpg; do
if convert -regard-warnings -- "$name" - >/dev/null 2>&1; then
printf 'Ok: %s\n' "$name"
else
printf 'Corrupt: %s\n' "$name"
fi
done
The above loop tries to convert each image, and if it fails to process an image file, it is detected by the if statement. We discard the result of the conversion operation.
| Bash script escaping quotes |
1,596,129,203,000 |
I have a directory with some .flac files:
[test]$ ls
'test file (with $ign & parentheses).flac' 'test file with spaces.flac'
I want to run an ffmpeg test command on those files, i used find with -exec argument to achieve this:
find ./ -type f -iregex '.*\.flac' -exec sh -c 'ffmtest=$(ffmpeg -v error -i "{}" -f null - 2>&1);if [ -n "$ffmtest" ];then echo -e "{}\n" $ffmtest;fi ' \;
Little explanation for my code:
The find command will find the .flac files and pass the names to the ffmpeg command for testing.
The ffmpeg command tests the file and return an error string to stdout(because of the redirection at the end) or nothing if no error is found, the if statement following the ffmpeg command is used so that if ffmtest variable contains an error then print the name of the file with the error followed by the error string(if the file contains no error then nothing will be printed).
My code works as expected but it fails if the filename contains a $ sign followed by a letter so for the test files mentioned above the output i get is this
[test]$ find ./ -type f -iregex '.*\.flac' -exec sh -c 'ffmtest=$(ffmpeg -v error -i "{}" -f null - 2>&1);if [ -n "$ffmtest" ];then echo -e "{}\n" $ffmtest;fi ' \;
./test file (with & parentheses).flac
./test file (with & parentheses).flac: No such file or directory
you can see that the test file with no $ sign was tested properly and ffmpeg didn't output any errors but it failed to even open the file with the $ sign in the name, you can see from the output of ffmpeg and echo that the filename was interpreted and the $ sign followed by the letters were treated as a variable.
So how can I tell find to escape such characters ?
|
The {} is replaced literally by the filename, so put it somewhere that it doesn't get parsed specially. Since you're already using sh -c, the argument position seems ideal:
find ./ -type f -iregex '.*\.flac' -exec sh -c 'ffmtest=$(ffmpeg -v error -i "$1" -f null - 2>&1);if [ -n "$ffmtest" ];then echo -e "$1\n" $ffmtest;fi' -- {} \;
| use find -exec with a filename containing a dollar sign ($) [duplicate] |
1,596,129,203,000 |
Do terminals ignore superfluous escape sequences silently?
#!/bin/sh
printf "\033[?25l"
printf "\033[?25l" # superfluous
printf "\033[31m"
printf "\033[31m" # superfluous
printf "Red Text\n"
sleep 1
printf "\033[0m"
printf "\033[?25h"
|
Yes, they do.
You might be familiar with certain document formats, e.g. HTML where opening and closing tags need to correspond to each other. E.g. this is okay:
<font style="color:red"><font style="color:red">foobar</font></font>
but this is not, since the tags are not balanced:
<font style="color:red"><font style="color:red">foobar</font>
Terminal emulation is not like this. The terminal emulator doesn't see an entire "document" at once, rather it sees an incoming stream as it arrives over time.
Terminal emulators are a state machine. Complete escape sequences, such as \033[?25l or \033[31m do not open or close contexts, they just set a certain new state. The first example here makes the cursor invisible, the second one switches to red font. You might execute them multiple times, the cursor doesn't become any more invisible and the text doesn't become any more red, nor will there be instances of these instructions remaining somewhere on the stack. These are one-time assignments: the cursor is made invisible (no matter what its previous state was), and the color for printing subsequent text is switched to red (again: no matter what its previous state was).
There are only a few escape sequences which have somewhat of an opening-closing semantics, e.g. you can push the current window title on a stack and later pop it from there, obviously these are supposed to be used in pairs.
| Do terminals ignore superfluous escape sequences silently? |
1,596,129,203,000 |
I'm outputting an echo -ne command to a file in my set-up script for a usb mouse HID.
Here is the script, which is run as root through /etc/rc.local at bootup:
#accidentally had a newline here <---
#!/bin/bash
cd /sys/kernel/config/usb_gadget/
mkdir -p isticktoit
cd isticktoit
echo 0x1d6b > idVendor # Linux Foundation
echo 0x0104 > idProduct # Multifunction Composite Gadget
echo 0x0100 > bcdDevice # v1.0.0
echo 0x0200 > bcdUSB # USB2
mkdir -p strings/0x409
echo "fedcba9876543210" > strings/0x409/serialnumber
echo "JW" > strings/0x409/manufacturer
echo "DoItForTheWenHua" > strings/0x409/product
mkdir -p configs/c.1/strings/0x409
echo "Config 1" > configs/c.1/strings/0x409/configuration
echo 0x80 > configs/c.1/bmAttributes
echo 250 > configs/c.1/MaxPower
# Add functions here
mkdir -p functions/hid.usb0
echo 1 > functions/hid.usb0/protocol
echo 1 > functions/hid.usb0/subclass
echo 3 > functions/hid.usb0/report_length
# NEXT LINE CAUSES ISSUES
echo -ne \\x05\\x01\\x09\\x02\\xa1\\x01\\x09\\x01\\xa1\\x00\\x05\\x09\\x19\\x01\\x29\\x03\\x15\\x00\\x25\\x01\\x95\02\\x81\\x06\\xc0\\xc0 > functions/hid.usb0/report_desc
ln -s functions/hid.usb0 configs/c.1/
# End functions
ls /sys/class/udc > UDC
The expected result of the echo -ne is a sequence of chars being written to file functions/hid.usb0/report_desc starting with 0x05, 0x01, 0x09, etc. Instead I got
$ cat /sys/kernel/config/usb_gadget/isticktoit/functions/hid.usb0/report_desc
-ne \x05\x01\x09\x02\xa1\x01\x09\x01\xa1\x00\x05\x09\x19\x01\x29\x03\x15\x00\x25\x01\x95\02\x81\x06\xc0\xc0
When I tried to test this, I couldn't reproduce it. Running the command in bash (works):
pi@raspberrypi:~ $ echo -ne "\\x05\\x01\\x09\\x02\\xa1\\x01\\x09\\x01\\xa1\\x00\\x05\\x09\\x19\\x01\\x29\\x03\\x15\\x00\\x25\\x01\\x95\\x03\\x75\\x01\\x81\\x02\\x95\\x01\\x75\\x05\\x81\\x03\\x05\\x01\\x09\\x30\\x09\\x31\\x15\\x81\\x25\\x7f\\x75\\x08\\x95\\x02\\x81\\x06\\xc0\\xc0"
▒ ▒ )%▒u▒▒u▒ 0 1▒▒▒▒▒
Running a test script (works):
pi@raspberrypi:~ $ cat test
▒ ▒ )%▒u▒▒u▒ 0 1▒▒▒▒▒
pi@raspberrypi:~ $ cat test.sh
#!/bin/bash
echo -ne "\\x05\\x01\\x09\\x02\\xa1\\x01\\x09\\x01\\xa1\\x00\\x05\\x09\\x19\\x01\\x29\\x03\\x15\\x00\\x25\\x01\\x95\\x03\\x75\\x01\\x81\\x02\\x95\\x01\\x75\\x05\\x81\\x03\\x05\\x01\\x09\\x30\\x09\\x31\\x15\\x81\\x25\\x7f\\x75\\x08\\x95\\x02\\x81\\x06\\xc0\\xc0" > test
pi@raspberrypi:~ $ ./test.sh
pi@raspberrypi:~ $ cat test
▒ ▒ )%▒u▒▒u▒ 0 1▒▒▒▒▒P
Bash redirect (works):
pi@raspberrypi:~ $ echo -ne "\\x05\\x01\\x09\\x02\\xa1\\x01\\x09\\x01\\xa1\\x00\\x05\\x09\\x19\\x01\\x29\\x03\\x15\\x00\\x25\\x01\\x95\\x03\\x75\\x01\\x81\\x02\\x95\\x01\\x75\\x05\\x81\\x03\\x05\\x01\\x09\\x30\\x09\\x31\\x15\\x81\\x25\\x7f\\x75\\x08\\x95\\x02\\x81\\x06\\xc0\\xc0" > test
pi@raspberrypi:~ $ cat test
▒ ▒ )%▒u▒▒u▒ 0 1▒▒▒▒▒
So, what did I do wrong here?
Answer: I didn't put the shebang on the right line, it caused another shell to interpret my script.
|
The behaviour of echo is notoriously unportable. Your script probably runs with some other shell when it doesn't work. (You're not running sh scriptname, are you?) See, e.g. how echo differs in Bash and Dash:
$ bash -c 'echo -ne \\x41\\x42\\x43\\x0a'
ABC
$ dash -c 'echo -ne \\x41\\x42\\x43\\x0a'
-ne \x41\x42\x43\x0a
Usually, it's better to use printf instead, but that alone won't help, as not all printfs support hex character escapes (\x00), only octals (\000) so you'd need to change the content too. In any case, in Bash printf \\x41\\x42\\x43\\x0a would do the same as Bash's echo -en \\x41\\x42\\x43\\x0a but slightly more portably.
You'll need to check what shell runs the script.
See also: Why is printf better than echo?
| Correctly Escape echo -ne [closed] |
1,596,129,203,000 |
I'm trying to use this line in a bash script to update my cron jobs:
(sudo crontab -l ; echo "0 6 1-7 * * [ $(/usr/bin/date +\%u) == 7 ] && sh $script_path > $log_path") | sort - | uniq - | sudo crontab -
Prior to this, $script_path and $log_path have been defined. I know this works in general. I just have one hang up. $(/usr/bin/date +\%u) resolves to an empty string when the crontab file is written to. I need that literal text to remain in place.
(Not that is really matters, but the point of that is to verify the day of the week. This job is to be run on the first Saturday of the month).
How do I "escape" that whole substring?
|
You may escape each problematic character with \ (see Hunter.S.Thompson's answer) or just use single quotes, the enclosed string being written as is:
(sudo crontab -l ; echo '0 6 1-7 * * [ $(/usr/bin/date +\%u) == 7 ] && sh '"$script_path > $log_path") | sort -u | sudo crontab -
I personally tend to avoid escaping characters, as I think it harms readability.
| Another Bash string escape question (using echo) |
1,596,129,203,000 |
My source of question is the answer here on this link, plus some extra things
UPDATE
I understand the first command i.e grep \\[[a-z\|1-9]*\\] file but I don't understand the output of second command i.e grep \[[a-z\|1-9]*\] file.
Now, I just want to understand how the output of second command is constructed especially why grep selected the whole third and fourth line completely, but selected the second and third line only up to the first ]
|
Lets walk slowly.
If there is a file with this content (in just one line to make it easier to show):
$ cat infile
list[1]; i[ab1]; var[1] [1]var [1]var[2]
a
A simple grep --color a will show in red all the a's.
(As this site does allow the control of colors : Assume that bold is red):
$ grep --color a infile
list[1]; i[ab1]; var[1] [1]var [1]var[2]
Exactly the same happens if the a is un-quoted (as above) or if it is quoted:
$ grep --color \a infile
list[1]; i[ab1]; var[1] [1]var [1]var[2]
$ grep --color "a" infile
list[1]; i[ab1]; var[1] [1]var [1]var[2]
$ grep --color 'a' infile
list[1]; i[ab1]; var[1] [1]var [1]var[2]
Why? Because the a's are both:
Not special to the shell.
The shell remove the quotes and grep receive the same a as first argument. Either a backslash quote, a double quote, or a single quote.
]
If we want to select the braces ] (lets start with the closing brace):
$ grep --color ] infile
list[1]; i[ab1]; var[1][1]var [1]var[2]
The same will happen if the ] were quoted (any quote).
In this case the ] is special to the shell but not in this case where there is no matching opening brace.
For a closing brace, things get one step more complex. All of this raise an error:
grep --color [ infile
grep --color '[' infile
grep --color "[" infile
Why? Because what grep receive in all cases is a single [.
You can undestand what the shell does with this simple echo:
$ echo \[ "[" '['
[ [ [
The shell remove one level of quoting and all values look the same.
[
But what grep wants to receive to undestand that we are actually searching for the character [ is a backslash quoted square brace (\[). That will happen with all of this:
$ echo \\[ "\[" '\['
\[ \[ \[
And grep will work with any of those:
$ grep --color \\[ infile
list[1]; i[ab1]; var[1][1]var[1]var[2]
[[]
Using [[] (a character list with only one character) will get to the same result (as long as it is quoted).
$ grep --color '[[]' infile
list[1]; i[ab1]; var[1][1]var[1]var[2]
Grep needs to receive exactly [[] for this to work. It may seem that no quotes are really needed:
$ echo \[\[\] "[[]" '[[]' [[]
[[] [[] [[] [[]
But if you create a file named [, that idea will break:
$ touch \[
$ echo \[\[\] "[[]" '[[]' [[]
[[] [[] [[] [
that is because the [ is special to the shell. To the shell, it starts a filename globbing pattern. If a file (or many) match the pattern, the list of files is substituted.
So, this will work correctly:
$ grep --color '[[]' infile
list[1]; i[ab1]; var[1][1]var[1]var[2]
And this: grep --color '[]]' infile will match the closing brace.
[][]
To match both the opening square brace and the closing square brace, you need an specific sequence of characters (quoted, of course).
If you try this:
$ grep --color '[[]]' infile
There will be no match, none at all. You need this to get it working correctly:
$ grep --color '[][]' infile
list[1]; i[ab1]; var[1][1]var[1]var[2]
In that specific order, the closing brace must be the first character inside the character range. The opening brace must be the last character in the character list.
[]a-z0-9[]
Then, you can add other characters (only not the ;):
$ grep --color '[]a-z0-9[]' infile
list[1];i[ab1];var[1][1]var[1]var[2]
And then, you can add the missing | in the range and do the match that is the link you posted. The regex in that link is not the same as here, and works in a very differnt way. It starts by matching one [, some other characters and end with a closing ]. Something similar to (the greedy nature of the * takes the whole line):
$ grep --color '\[.*\]' infile
list[1]; i[ab1]; var[1] [1]var [1]var[2]
Or also similar to this:
$ grep --color '[[][a-c0-9]*[]]' infile
list[1]; i[ab1]; var[1][1]var[1]var[2]`
| Understanding Escaping |
1,596,129,203,000 |
I recently tweaked a bit my PS1. The code as follows:
PS1='$(if [[ $? != 0 ]]; then echo " \e[91m\e[0m"; fi) \u $(assemble_prompt)$ '
The missing char is from nerd-fonts and doesn't matter in my question (as well as assemble_prompt function).
The problem I encountered is a broken PS1 when I shrink terminal window size to the size of a prompt (approx.). Then it seem to ignore PS1 setting and sets PS1 to $ chars only (see screenshot). Note then when I start typing it simply overrides my custom prompt in this occasion.
I narrowed the problem to an if clause that adds "fail" char if previous command was unsuccessful. If I remove that part everything works as expected.
Is there a way to keep if clause part but fix the issue with PS1 reset when the window size is too small?
P.S. I use rxvt-unicode as my terminal but the problem persists in all other terminals also (tested xterm, st).
|
You probably want to enclose the terminal control codes in \[...\] to tell Bash that they aren't actually printing characters. Otherwise they will confuse the shell when tries to count how wide the prompt is.
So use "\[\e[91m\]xxx\[\e[0m\]".
From the manual:
\[ Begin a sequence of non-printing characters.
This could be used to embed a terminal control sequence into the prompt.
\] End a sequence of non-printing characters.
| Prompt customization problem with if clause |
1,596,129,203,000 |
I have learned about formatting options used in shell scripting, which go like this:
\033[37:40mAnyText\033[0m
Now I want to echo some text like this:
echo -e "SomeText \033[5;31;47mMoreText\033[0m"
The integer 5 is for blinking. The other formatting works, but not the blinking -- why?
|
This is a terminal independent way of enabling the blinking attribute. If it doesn't work then either you've mis-set your terminal type, it's not enabled in the terminal characteristics, or it's simply not supported:
tput blink
echo hello, world
tput sgr0
The terminfo database is well worth perusing (not bedtime reading, mind) to find semi-readable names for terminal escape code sequences.
| Create blinking text with echo and escape characters [duplicate] |
1,596,129,203,000 |
How can the following list of commands can be quoted separately?
s="cp
mkdir
[[
mv
rm"
quoted_s= ????
This should be the output of echo $quoted_s:
cp
mkdir
\[\[
mv
rm
Using ${(q)s} or ${(qq)s} quotes them together:
$ echo ${(qq)s}
'cp
mkdir
[[
mv
rm'
|
In this case, you could use the b expansion flag. From info zsh flag or man zshexpn:
b Quote with backslashes only characters that are special to pat‐
tern matching.
So given
~ % print -r -- $s
cp
mkdir
[[
mv
rm
then
~ % print -r -- ${(b)s}
cp
mkdir
\[\[
mv
rm
More generally, you could split on newlines, apply q to the result, and re-join:
~ % print -r -- ${(F)${(qf)s}}
cp
mkdir
\[\[
mv
rm
or with a csh-style postfix modifier
~ % print -r -- ${(F)${(f)s}:q}
cp
mkdir
\[\[
mv
rm
or even (letting print add back the newlines)
% print -rC1 -- ${(qf)s}
cp
mkdir
\[\[
mv
rm
(-C1 to print on 1 Column has the advantage over -l that if there's no argument, nothing is printed as opposed to one empty line).
Note that the b, q, qq, qqq, qqqq, q-, q+ flags and :q modifiers produce different kinds of quoting, pick the one that suits you best for your particular use case.
Whatever you do don't forget the --. Omitting it introduces arbitrary command injection vulnerabilities, the worst kind of vulnerability.
| zsh: How can I escape each word separately? |
1,596,129,203,000 |
I am learning ECMA-48 and I see a lot of notes about 7 bit and 8 bit environments for control functions. For example:
NOTE LS0 is used in 8-bit environments only; in 7-bit environments
SHIFT-IN (SI) is used instead.
Could anyone explain the difference between them and give real examples when each of them is used.
|
Very early printers might have two colours on the ribbon, like mechanical typewriters did. SI and SO switched between the optional colour and the normal colour. Note that this is not the same usage as the shift key!
Early printers and terminals (I'll call them all just terminals from now on) used a 7-bit ASCII code. Typically the eighth bit was used as parity, but this had to be configured. To allow for additional characters some terminals had additional built-in character sets, or else the ability to download them. To switch between them SI and SO were hijacked. For instance to print in Katakana you would send SO, and later to go back to Latin-1 send SI.
As eight-bit systems became more common additional control codes became available. Two of the additional codes were SSI and SSO where "SS" stands for single shift. For instance to print a single graphical character you might use rather than having to send <glyph which runs the risk of the screen turning into "hieroglyphs" as my users used to call them. To distinguish between these modes, the original SI and SO were renamed LSI and LSO (ie Locking Shift) but retained their original behaviour.
So to summarise LSI=SI and LSO=SO, it's just the names that vary between the two environments.
As an example: suppose that I had the UK character set as my default. I wish to quote a bit of French, let's say "garçon". I would send down the line 67 61 72 0E 5C 0F 6F 6E. Note the 0E and 0F surrounding the 5C, without that the glyph backslash would have been printed.
I've nabbed the details from the "LA75 Companion Printer: Programmer Reference Manual" published by digital, but any 1980s or 1990s printer or terminal manual should show broadly the same. Details do vary between models and over time though.
| What are 7 bit / 8 bit environments for control functions according to ISO/IEC 6429:1992? |
1,596,129,203,000 |
It is possible to pass resources to X applications in command-line by appending them with -xrm parameters. So, if I want Xmessage background to be grey, I can issue xmessage Hi -xrm "xmessage*background: grey".
Things get tricky if I want to modify event translations. On my .Xresouces, this
Xmessage*Translations:#override\
<Key>F10:exit(-1) \n\
<Key>q:exit(-1)
succeeds in setting F10 and q keys to exit any Xmessage window, but I'm having trouble doing it with -xrm in command line, certainly because of the newlines and escaping backslashes.
I've tried the three following commands, but without success.
xmessage Hi -xrm "xmessage*Translations:#override <Key>s:exit(4)
<Key>r:exit(3)
<Key>p:exit(2)"
xmessage Hi -xrm "xmessage*Translations:#override\
<Key>s:exit(4)\n\
<Key>r:exit(3)\n\
<Key>p:exit(2)"
xmessage Hi -xrm "xmessage*Translations:#override <Key>s:exit(4)" \
-xrm "xmessage*Translations:#override <Key>r:exit(3)" \
-xrm "xmessage*Translations:#override <Key>p:exit(2)"
The 3rd command only assigns the last key successfully. The others fail, although I expected the 1st to work, since it inserts a newline after exit(4) and exit(3), as confirmed by echoing the command.
What am I missing and how can I correct it?
|
You need to put in single quotes :
xmessage Hi -xrm 'xmessage*Translations:#override\
<Key>F10:exit(-1) \n\
<Key>q:exit(-1)'
Otherwise, newlines get lost.
| Trouble passing Translations resource to -xrm because of newlines |
1,596,129,203,000 |
I am trying to take a filename from the ~/Pictures folder and supply it as an argument for the nomacs command. The filename contains some spaces, so I am using Bash substitution to escape spaces (I also want to take last file in the folder).
The code:
names=$(\ls ~/Pictures * | tac)
SAVEIFS=$IFS
IFS=$'\n'
names=($names)
IFS=$SAVEIFS
screenshot=~/Pictures/${names[0]}
screenshot=${screenshot// /\\ }
nomacs $screenshot
Example of the filename: Screenshot from 2017-09-13 18-05-42.png
The problem is that nomacs $screenshot does not work but when I execute nomacs Screenshot\ from\ 2017-09-13 18-05-42.png, it works as expected.
Should I use some special Bash technique for escaping spaces?
|
From what I gather from your script, you're reversing the output of ls and selecting the first item. Here's a different way to do that with bash:
files=(~/Pictures/*)
nomacs "${files[-1]}"
This fills an array with the glob expansion of ~/Pictures/* then passes the last element to the nomacs program.
| Providing argument to a command after substitution |
1,596,129,203,000 |
I'm using the jq tool to handle some JSON in bash.
Just one problem, while using this line:
PB_ACL="acl="`echo $IMGREQ | jq -r'.data.acl'`
Result:
echo $PB_ACL // acl=
The expected value jq has to filter out is: "acl":"public-read"
But it's not working now. I think it has to to with the dash (-) symbol.
How do I escape such incoming string data?
|
Missed a space:
PB_ACL="acl="`echo $IMGREQ | jq -r '.data.acl'`
^
| How to escape an input string in Bash [closed] |
1,596,129,203,000 |
I have a long command and I just want to use alias to shorten it. But the command contains single quotes and exclamation marks.
The origin command is ldapsearch -x -H ... -w 'abc!123'.
I tried alias search='ldapsearch -x -H ... -w \'abc!123\'' or alias search="ldapsearch -x -H ... -w 'abc!123'" and so on. But none of them works for me.
|
! is only a problem for history expansion. History expansion only happens in interactive shells (when not disabled altogether by the user like I do) and in bash (like in zsh, but contrary to csh where both history expansion and aliases come from) happens before alias expansion and is not done again after aliases are expanded, so it's fine to leave a ! unquoted in the value of an alias:
alias search='ldapsearch -x -H ... -w abc!123'
That alias command will be fine even if run in an interactive shell because in bash (again like in zsh but contrary to csh), single quotes prevent !, ^... from triggering history expansion.
To have the ! single quoted in the value of the alias, you'd have to do things like:
alias search='ldapsearch -x -H ... -w '\'abc\!123\'
alias search=$'ldapsearch -x -H ... -w \'abc!123\''
alias search='ldapsearch -x -H ... -w '\''abc!123'\'
alias search="ldapsearch -x -H ... -w 'abc"\!"123'"
alias search=ldapsearch\ -x\ -H\ ...\ -w\ \'abc\!123\'
That is make sure the ! is quoted by either '...', $'...' or \ (outside of any other form of quotes) not double quotes.
Using "abc!123" works in non-interactive shells, but not in interactive ones. "abc\!123" work in interactive ones but not non-interactive ones.
Instead of an alias, you can use a function (aliases got popular because they appeared in csh (circa 1979) before the Bourne shell added functions (circa 1983), but they're really a wart in the face of shells these days).
search() { ldapsearch -x -H ... -w 'abc!123' "$@"; }
Or even possibly better, make it a:
#! /bin/sh -
exec ldapsearch -x -H ... -w 'abc!123' "$@"
Then you'll be able to call it from anywhere, not just your interactive shells.
Now passing a password on the command line is very bad practice as command line arguments are public information on most systems. They show up in the output of ps -f, they are stored in shell histories or audit log.
Instead you should use something like:
search() {
ldapsearch -x -H ... -y ~/.config/secrets/ldap/host.password "$@"
}
With ~/.config/secrets/ldap/host.password being readable only to yourself and containing the password, or:
search() {
ldapsearch -x -H ... -y <(
command-that-retrieves-the-password from your password manager
) "$@"
}
| How to escape both single quotes and exclamation marks in bash |
1,596,129,203,000 |
I have a script that finds some directories and then copies their content to another directory.
now the problem is that some of the found directories need to have brackets in their naming and they look something like this:
/directory/with/[brackets]
and cp says that there is no such file or directory when it tries to copy it like this:
cp -r /directory/with/[brackets]/* /some/other/directory
Now I figured out that the brackets need to be escaped in order for this to work and I just need a simple solution for that.
|
You basically have two options:
Escape using quotes:
cp -r "/directory/with/[brackets]"/* /some/other/directory
or
cp -r '/directory/with/[brackets]'/* /some/other/directory
Escape using backslashes:
cp -r /directory/with/\[brackets\]/* /some/other/directory
| How do I escape opening and closing brackets [] to use with cp command? |
1,596,129,203,000 |
I'm trying to add a history fuzzyfind hotkey to my bash shell. However, my intended command gets cut in the middle:
[april@Capybara-2:~]$ cat ~/.bashrc
bind "\"\C-r\": \"\$(history | fzf | awk '{\$1=\"\"; print substr(\$0,2)}')\""
[april@Capybara-2:~]$ $(history | fzf | awk '{$1="";
(The second line is the result when \C+r is pressed.)
I anticipated that \C+r should be bind to $(history | fzf | awk '{$1=""; print substr($0,2)}'), but that's not the case. Why?
|
It's quoting hell. You have the command in double quotes, so the \"\" becomes "", so for Readline, the command looks like:
bind "\C-r": "$(history | fzf | awk '{$1 = ""; ....
See the problem? The string started at "$( is ended by the first double quote in "";, I'm not sure how exactly string concatenation works for Readline, but it seems like any non-whitespace characters immediately after the closing quote are appended and everything else discarded.
We can fix the quoting accordingly, by using any of:
# Extra backslashes inside double quotes
bind "\"\C-r\": \"\$(history | fzf | awk '{\$1=\\\"\\\"; print substr(\$0,2)}')\""
# Wrap the macro in single quotes instead of double quotes
bind "\"\C-r\": '\$(history | fzf | awk \'{\$1=\"\"; print substr(\$0,2)}\')'"
# Use single quotes for the `bind` command argument instead of double quotes
bind '"\C-r": "$(history | fzf | awk '\''{$1=\"\"; print substr($0,2)}'\'')"'
| Problem with bash builtin bind and escaping |
1,596,129,203,000 |
I want to make a bash alias of the following command, which works typed out on the command line but all my attempts at making an alias have failed. My only diagnosis is that all those nested quotes and the loop are scary and I don't know how to handle them.
sudo ss -x src "*/tmp/.X11-unix/*" | grep -Eo "[0-9]+\s*$" | while read port
do sudo ss -p -x | grep -w $port | grep -v X11-unix
done | grep -Eo '".+"' | sort | uniq -c | sort -rn
Is it possible to alias this command?
|
For anything more complicated than, say, adding an option to some command, use shell functions rather than aliases.
Here's a function, mything, that you would define in the same place where you would ordinarily define aliases, which runs the command s that you show:
mything () {
sudo ss -x src "*/tmp/.X11-unix/*" |
grep -Eo "[0-9]+\s*$" |
while read -r port; do
sudo ss -p -x | grep -w "$port"
done |
grep -v X11-unix | grep -Eo '".+"' |
sort | uniq -c | sort -rn
}
I haven't looked closer to the actual commands that you are running (apart from fixing the unquoted use of $port and moving one grep out of the loop), but it seems like at least some of the operations may be replaceable by awk and you should be able to remove that loop or at least move sudo ss out of it. The main thing is that if you have something even remotely complicated to run, create a shell function for it.
| Bash alias with a loop, a sudo, pipes, flags, single quotes and double quotes |
1,596,129,203,000 |
I have the following Problem, I need an environment variable that contains globbing characters as clear text, and I can't seem to escape them. Escaping with backslash works, but for some reason the backslash is still part of the string."
Disabling GLOB_SUBST resolves the problem, but I´d like to avoid that.
I used the following to narrow down the problem:
touch foo; chmod +x ./foo
# glob expansion i.E. $test contains all files in the directory.
echo 'export test="*"; echo $test' > foo; source ./foo
# no glob expansion, but the escape character is added to the string.
echo 'export test="\*"; echo $test' > foo; source ./foo
# output: \*
Any help would be appreciated.
|
In the first case, you assign the string * to the variable, and since globsubst is enabled, the unquoted expansion $test is subject to globbing (as in a POSIX shell). In the second case, you assign the string \*, but it's not expanded as a glob since the backslash escapes the asterisk. (Otherwise zsh would complain that there were no matching files found, unless you've disabled that, too. You probably don't have filenames starting with a backslash anyway, but the glob to match them would have to be \\*.)
To stop the globbing, quote the variable expansion, i.e. echo "$test".
See: When is double-quoting necessary?
Also, you don't need export if you're just going to use the variables within the same shell (even between the main shell and the sourced script).
| Properly escaping asterisk/glob in (z)sh script |
1,596,129,203,000 |
In my current project, I am trying to take the output from git branch -r to an array in zsh, as follows:
% all_branches = ("${(@f)$(git branch -r)}")
However, when I run this command, I get the following error message on the terminal:
zsh: bad pattern: ( origin/Backplane-Broken-Links
I'm inferring that zsh is taking issue with the forward slash in the branch name. Is there a way I can process the forward slashes (as well as other special characters, if I run into any others) when sending the output from git into my array?
|
array assignment syntax in zsh (like in bash which borrowed that syntax from zsh) is:
array=( value1 value2
value3...)
There can't be whitespace on either side of = (though there can be (space, tab or newline) inside the (...) which are used to delimit the words as usual, and those words making up the array members).
So you want:
all_branches=("${(@f)$(git branch -r)}")
Or:
all_branches=( "${(@f)$(git branch -r)}" )
Or:
all_branches=(
"${(@f)$(git branch -r)}"
)
Whichever style you prefer.
all_branches=(${(f)"$(git branch -r)"})
Would also work. Placing the whole expansion in "..." combined with the @ flag is when you want to preserve empty elements. I don't think git branch names can be empty, and note that anyway $(...) strips all trailing newline characters, so empty branches would be removed anyway if they were at the end of the output. We still need $(...) to be quoted though to prevent $IFS-splitting.
Incidentally, array = () would be the start of the definition of both the array and = function:
$ array = ()
function> echo test
$ array
test
$ =
test
While:
array = (foo|bar)
Would be running the array command (if found) with = and the files that match the (foo|bar) glob pattern (if any) as argument.
But here, your ("${(@f)$(git branch -r)}") doesn't form a valid glob pattern, nothing to do with slashes.
For completeness,
array = ( value1 value2 )
is valid syntax in the rc shell (the shell of Research Unix V10 and plan9). In that shell, you can't do echo = which gives you a syntax error. You need to quote the =.
| Escape slashes when sending command output to an array [duplicate] |
1,596,129,203,000 |
I have another question about ANSI Art. The problem is this file https://16colo.rs/pack/lgcy-003/hayn9-smaller.ans
It have "à" character (the women in ANSI Art have it inside medalion on her neck).
And just before that, there is this sequence of ANSI Escape codes:
[0;5;30mà
In Difference between ANSI art and Linux Terminal ANSI escapes codes I was told that 5m works the same as bold 1m, but something else need to happen here because it some how get gray background and black color. Even that 30 is Foreground Black which for bold it should make it gray color on black background.
Can someone explain what this sequence should do in ANSI Art?
The only way to make this work is if 5 is reversed colors and bold.
|
Found the answer in blocktronics/moebius ANSI Art editor source code on GitHub.
The blink flag change bold only for the background. And normal bold change bold for color.
This can be found in this file app/libtextmode/ansi.js@0ff8f66#L203.
| Problematic [0;5;30m ANSI Code in ANSI Art |
1,596,129,203,000 |
Many non alpha-numeric characters appear as jumbled mess when using less and man.
Currently, I'm using zsh but the same problem happens in bash and sh.
The problem also appears in both the st and termite terminal emulators.
man grep produces:
How can i fix this?
env -i TERM=$TERM PATH=/usr/bin:/bin HOME=/none man grep renders correctly.
|
Since the problem disappears with a minimal environment, it's caused by an environment variable. It turns out to be your LESS_TERMCAP settings. You've set them to sequences beginning with [. They're missing the initial escape character.
csi=$(printf '\033[')
export LESS_TERMCAP_mb="${csi}1;31m"
…
| Extra characters appear in `less` |
1,596,129,203,000 |
i have command like this
date -d @$(date -d 'Sat, 08 Aug 2020 00:00:00' "+%s") +'%Y-%m-%d'
which output this
2020-08-08
So i want to use thins in bash scrip, i created this (this is just part of realy big script)
Date1=$1
date -d @$(date -d $Date1 "+%s") +'%Y-%m-%d'
But when i try to run like this
./test.sh "Sat, 08 Aug 2020 00:00:00"
I get
date: extra operand ‘Aug’
Try 'date --help' for more information.
date: invalid date ‘@’
So its look like that "" desapear when passing argument
|
Wrap your $Date1 inside the quotes and it should work:
date -d @$(date -d "$Date1" "+%s") +'%Y-%m-%d'
See also When is double-quoting necessary?
| Bash scrip passing argument in quotes |
1,596,129,203,000 |
I am doing some automation with shell scripting and I am having trouble running a python script in which its' path has spaces. Forgive me if I made any mistakes or bad practices in the code, I just started learning yesterday :).
Here is the code:
# grabs root directory from the script path
script_path="$( cd "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"
proj_root="${script_path///modelsim}"
proj_root="${proj_root///test}"
# removing spaces
proj_root_no_spaces="${proj_root/' '/'\ '}"
log_dir=${proj_root_no_spaces}/src/python/graph_log.py #path to python file relative to root project dir
# checking output
echo "$log_dir"
create_graphs="python3 \""$log_dir"\""
echo "$create_graphs"
# run command
$create_graphs
This script gives this output:
1) /mnt/c/Users/Varun\ Govind/Desktop/roulette_BACKUP/roulette/src/python/graph_log.py
2) python3 "/mnt/c/Users/Varun\ Govind/Desktop/roulette_BACKUP/roulette/src/python/graph_log.py"
3) python3: can't open file '"/mnt/c/Users/Varun\': [Errno 2] No such file or directory
The first line is the full path to the python file, you can see that there is a space in between my user name so I escaped it with a backslash. The second line is the full python command that I am running; in addition to escaping the space, I've surrounded the path with double-quotes. If I run that however, I get an error on line 3.
If I copy and paste line 2 directly into my shell, and run it, it works. I'm not sure why my command isn't working in my shell script. Is there something wrong with how I am escaping the spaces or running the python command?
|
Short answer: See BashFAQ #50: I'm trying to put a command in a variable, but the complex cases always fail!
Long answer: Don't try to embed shell syntax (like quotes and escapes) in variables; variables are for data, not syntax. Instead, just put double-quotes around variable references (i.e. put the quotes around the variable, not in the variable). For the same reason, don't try to store commands in variables, just execute them directly.
Thus, skip proj_root_no_spaces and just store the path, unescaped spaces and all:
log_dir=${proj_root}/src/python/graph_log.py #path to python file relative to root project dir
Then don't store the python3 ... command in create_graphs, just execute it directly:
python3 "$log_dir"
| Issue running a python script in shell script that has spaces to the python script |
1,596,129,203,000 |
Context:
I use zsh and use vi editing mode. To go up in the history instead of pressing ESC to go to the normal mode and pressing k, I press alt+k which sends the esc character and sends k afterwords (as per my understanding)
Problem:
It works fine until I start a ssh session, even after closing the session it doesn't work. Instead, when pressing alt+k it inserts ë character.
Current Understanding:
This is something to do with the terminal and not the shell. However, opening a SSH session changes some runtime property of the terminal which I couldn't think of.
st git commit: 63776c0962874dfab135a595a765b4d3b5fbcb65 (current master)
Any idea that helps is greatly appreciated.
PS: I have a very little understanding of how the terminals work internally.
|
There is an old way of signalling "meta", which assumes that you are using a 7-bit character set and that it is free to fiddle with the high bits of characters.
It doesn't really work well with 8-bit character sets let alone UTF-8, producing characters confusing to the uninitiated as you have seen.
Only some terminal emulators support it, including XTerm and Simple Terminal, and it is turned on and off with ECMA-48 vendor-private Set/Reset Mode control sequences, parameter 1034.
In terminfo terminology, this is "meta mode".
The program on the remote system that you accessed over SSH turned on "meta mode" for some reason and didn't turn it back off again.
You can turn off meta mode by printing the DECRST 1034 control sequence directly with (say) printf: printf '\e[?%ul' 1034 or with the (terminfo version of the) tput command: tput rmm
Incidentally: Don't expect the setmetamode command from the kbd package (on operating systems like Debian Linux) to work, as that uses an idiosyncratic way of changing this mode that is specific to the Linux built-in virtual terminal.
| st terminal + shell vi mode |
1,596,129,203,000 |
I have a script which i want to auto-login inside a mysql database.
The problem is when the password has special characters, here an example:
Password file contains:
password=$AES-256$VlQ==$+rZfd6ntjZdyD0=
And this is the script:
pass=$(cat password_file | grep password | cut -d"=" -f2)
mysql -uroot -p$pass
How could this be done? Maybe trying to escape
I know even the cut part is just cutting the password in half.
|
You can try this with GNU grep:
grep -Po "(?<=^password=).*" file
With sed
grep "^password" file | sed 's/[^=]*=//'
With awk:
awk -F'password=' '{ print $2 }'
| Scripting login to mysql with a string with special characters |
1,596,129,203,000 |
I have been looking for this question everywhere, but I didn't find it and there doesn't seem to be any kind of answer yet to my current problem, which, frankly, doesn't even make sense.
So, what I want to do is escape the question mark ? in my variable declaration. Obviously writing
var=?
won't do it. Of course, you would then use backslash along with the question mark to solve the problem, usually:
var=\?
However: This doesn't work (but it actually should). When echoing the variable, it actually outputs:
5 A X
(these are three folders in my home directory)
Then I noticed this happened when I was in my home directory, or in a directory like root (where I have the folders A, B and C). So, I changed cwd to to an empty, newly created directory and suddenly it worked. What exactly could be the cause of this? It only seems to happen with one letter folder names, but I thought this isn't supposed to happen since I escape the question mark with \?
|
You should quote the variable in your echo command:
$ var=?
$ echo "$var"
?
| Cannot escape '?' character in variables (unix) |
1,596,129,203,000 |
I am trying to use a newline in bash. I found that I need ANSI C quoting for that (i.e. $'\n'), but this often does not work for me. So I am wondering what I am doing wrong.
# This works
>> echo $'a\nb\nc'
a
b
c
# This doesn't
>> A=$'a\nb\nc'
>> echo $A
a b c
# Also, this does not work
>> A="a b c"
>> echo ${A// /$'\n'}
a b c
If I use tab instead of newline, I have the same problems. Other ANSI C quoting work like \', or \", or even \b.
GNU Bash; version: 4.3.11(1)
|
Because you've not quoted the variable in:
echo $A
it is subject to splitting and globbing. The first step is the expansion of the variable's contents:
echo a $'\n' b $'\n' c -- where the $'\n' bits represent actual newlines.
Then, the various pieces are split on $IFS, resulting in:
echo a b c
Then, since there are no wildcards to generate additional filenames, the strings are passed on to echo.
When you quote the variable, with echo "$A", you inhibit splitting and globbing.
See the change yourself if you modify IFS:
oIFS=$IFS
IFS=
echo $A
IFS=$oIFS
| ANSI C quoting for tab and newline sometimes does not work |
1,596,129,203,000 |
I have a pretty big json file and I would like to add the escape character in front of all quotation marks in it. For example I want to change:
"CaptureDuration":0 to \"CaptureDuration\":0. I tried to substitute all " with \" in sed and vim but I guess due to the special type of the escape character it wasn't working properly.
|
Use sed and you needed to escape \ as it's special character:
sed 's/"/\\"/g' infile
| Add escape character in front of all quotation marks in a file |
1,511,064,482,000 |
I’m trying to create a ls-like function.
I started with this alias, which works fine:
alias l="/usr/bin/ls -lF --color=always | tr -s ' ' | cut -d ' ' -f 9-"
However, converting it to a function results in no colors:
l() {
local _c=
[ -t 1 ] && _c=--color=always
/usr/bin/ls -lF $_c "$@" | tr -s ' ' | cut -d ' ' -f 9-
}
Even removing all differences from the alias to the function remains colorless:
l() {
/usr/bin/ls -lF --color=always | tr -s ' ' | cut -d ' ' -f 9-
}
The only colored variant is one without oipe
l() {
/usr/bin/ls -lF --color=always
}
What prevents the color from passing through the pipes in functions?
|
Are you sure you haven't got an l alias that is either interfering with the function definition or being used before the function: aliases take precedence over functions. And are expanded even for a function definition.
| escape sequence behaving differently in function |
1,511,064,482,000 |
I want to backslash a variable automatically so that the end users don't need to type the backslashes for a Perl regex string replacement.
API_URI="http://something/api"
FIND="(API_URI)(.*?[\=])(.*?[\'](.*?[\']))"
REPLACE="\\1\\2 \'$API_URI\'"
perl -pi -e "s/${FIND}/${REPLACE}/" file.ext
|
By all means use Perl if you want to, but doesn't this sed do the trick?
echo "$API_URI" | sed 's/\//\\\//g'
http:\/\/something\/api
Or... in straight Bash:
echo "${API_URI//\//\\/}"
http:\/\/something\/api
| How to backslash a dynamic string in bash |
1,511,064,482,000 |
I want to remap my F9 key to the dollar sign ($) symbol.
So I ran this command
bind '"\e[20": "$"'
Now whenever I type the F9 key, instead of getting just
$
I get
$~
Why is the extra tilde there and how can I get rid of it?
|
Try this:
bind '"\e[20~": "$"'
To determine character sequence for a key press,
Press Ctrl+v and press the key for which you want to get the character sequence.
Example:
For key F9, I get ^[[20~ where ^[ is Esc key and remaining sequence is for F9.
| Why does my binded key result in an extra tilde? |
1,511,064,482,000 |
My text in vim looks like,
i am one line
i come in next line
i come after a tab space
Can the above text be converted like this,
i am one line\ni come in next line\n\ti come after a tab space
|
From my understanding of your question you want to convert newlines to the literal sequence backslash followed by n and convert tabs to the literal sequence backslash followed by t.
For replacing the tab character, sure, no problem, it's the same as normal string replacement. Try this:
:%s/\t/\\t/
Note: the recognition of escape sequences like \t in search patterns may only work in Vim. I'm not sure. If it does not work in your vi then you must type an actual tab character in that location. The tab will show up as ^I (but it is not the same as ^ followed by I).
:%s/^I/\\t/
For the newline, try the same thing:
:%s/\n/\\n/
Again, this might be Vim-only, I'm not sure. For replacing newlines, you may be out of luck in regular vi because vi is fundamentally a line-based editor.
| In vi, convert invisible characters into escape sequences? |
1,511,064,482,000 |
I have some shortcut keys defined in iTerm, and I use them for key-mappings in Vim.
For example, I map Ctrl-Enter to send a ^[O2P escape code, which I then use to define a Ctrl-Enter key-mapping in my Vim:
set <F13>=O2P
map <F13> <C-CR>
inoremap <C-CR> <C-O>o
It works in a regular iTerm session, and in a screen session, but it not in a tmux session. How can I fix this to work with tmux? I'm transitioning away from screen and really enjoying tmux aside from this hangup.
|
I got this working by adjusting the escape codes to watch for in my .vimrc.
I still wish I had a better understanding of how all this works, and why the sequence sent by tmux differs from what's sent outside of tmux, but this got everything working:
if &term =~ "screen"
set <F13>=[1;2P
set <F14>=[1;2Q
set <F15>=[1;2R
set <F16>=[1;2S
set <F17>=[1;5P
set <F18>=[1;5Q
set <F19>=[1;5R
set <F20>=[1;5A
set <F21>=[1;5B
elseif &term =~ "xterm"
set <F13>=O2P
set <F14>=O2Q
set <F15>=O2R
set <F16>=O2S
set <F17>=O5P
set <F18>=O5Q
set <F19>=O5R
set <F20>=[1;5A
set <F21>=[1;5B
endif
" use some unused function key codes to
" make special key combos work in terminal
map <F13> <C-CR>
map! <F13> <C-CR>
map <F14> <S-CR>
map! <F14> <S-CR>
map <F15> <C-Space>
map! <F15> <C-Space>
map <F16> <S-Space>
map! <F16> <S-Space>
map <F17> <C-BS>
map! <F17> <C-BS>
map <F18> <M-Tab>
map! <F18> <M-Tab>
map <F19> <M-S-Tab>
map! <F19> <M-S-Tab>
map <F20> <C-Up>
map! <F20> <C-Up>
map <F21> <C-Down>
map! <F21> <C-Down>
| Can I get my iTerm key-combos working in tmux? |
1,511,064,482,000 |
I have the following at the bottom of my ~/.bashrc which shows the last command run and the current working directory at the time of the last command in the title of my terminal window.
trap 'echo -ne "\033]2;$(history 1 | cut -d" " -f3-) ••• $(pwd)\007"' DEBUG
If I remove this, then URxvt functions as expected with \n and \t. Here is the expected behavior (which functions properly with other terminals, for example lxterminal).
~$ echo -e "thank\tyou"
thank you
However, URxvt does the following:
~$ echo -e "thank\tyou"
you" ••• /home/brockthank you
I have tried omitting different parts of the command in my ~/.bashrc but have not had any luck. I know that the development of URxvt stopped in 2016, but I really like it.
|
trap 'last_cmd=$(history 1 | cut -d" " -f3-); echo $last_cmd ••• $(pwd) | awk '\''!/\007/ {printf "\033]0;%s\007", $0}'\' DEBUG
| URxvt not working properly with backslash characters \n and \t (given my particular ~/.bashrc configuration) |
1,511,064,482,000 |
I am receiving a query via a configuration file in unix, for ex. Config file content will be in the format:
Table_name|query
ABC|select ABC.A,ABC.B from PQR left join (select * from ABC) on ABC.pk=PQR.pk
I am trying to process query part as below :
while read line in config_file
do
query=`echo $line|awk -F "|" '{print $1}'`
result=hive -e "$query"
...
However the '*' in query variable is getting expanded to the listing of files in the current directory
Could you please help how to escape the * character, i searched for the solution but could not find one.
|
Hi Saket Mankar and welcome to the community!
You would need to enclose the $line variable with double quotes: "$line".
That should solve your situation.
| Processing parameters with * passed to unix [duplicate] |
1,511,064,482,000 |
When running ls in terminal, output is variously colored:
AFAIK this colorasing is accomplished by espace sequences (vt).
But running ls | hexdump -cC shows only characters and LFs. Redirection to file leads to similar results.
How is that?
|
GNU ls only outputs escape sequences for colorized text when writing to a terminal, not when redirected to a file or pipe.
For that, use ls --color=always.
The GNU ls manual says:
Using color to distinguish file types is disabled both by default and
with --color=never. With --color=auto, ls emits color codes only when
standard output is connected to a terminal. [...]
I'm guessing that your ls command behaves like ls --color=auto by default, possibly through the use of an ls alias.
| Why don't I see escape sequences in redirected stream OR how is color output implemented? [duplicate] |
1,511,064,482,000 |
I don't understand this escaping. Is some generator available for it?
i need replace normal text (185...) with Variable $NEW_DNS
sed -i "185.228.168.168,185.228.169.168|$NEW_DNS /etc/wireguard/wg0.conf
Output
sed: -e expression #1, char 4: unknown command: `.'
Update:
i have like you can see answers and its work, just /etc/wireguard/wg0.conf is not rewrited with new Data (but Output from is correct.
# client start menu
echo "What can i do for you today? "
options=("Show Clients" "Show your DNS Server" "Change your DNS Server" "Install/add new Client" "Quit")
select opt in "${options[@]}"
do
case $opt in
"Show Clients")
ls *.conf
;;
"Show your DNS Server")
if [ $( head -n1 $CONF | awk '{print $5}') == "1.1.1.1,1.0.0.1" ]; then
echo "Your Public DNS Server is Cloudflare (1.1.1.1,1.0.0.1), great unfiltered choice for best speed worldwide! "
fi
if [ $( head -n1 $CONF | awk '{print $5}') == "176.103.130.130,176.103.130.131" ]; then
echo "Your Public DNS Server is Adguard (176.103.130.130,176.103.130.131), Advertising Filter kill them all! "
fi
if [ $( head -n1 $CONF | awk '{print $5}') == "84.200.69.80,84.200.70.40" ]; then
echo "Your Public DNS Server is WATCH.DNS (84.200.69.80,84.200.70.40), great unfiltered choice for German Clients! "
fi
if [ $( head -n1 $CONF | awk '{print $5}') == "9.9.9.9, 149.112.112.112" ]; then
echo "Your Public DNS Server is QUAD9 (9.9.9.9, 149.112.112.112), great TLS encrypted unfiltered choice! "
fi
if [ $( head -n1 $CONF | awk '{print $5}') == "77.88.8.7,77.88.8.3" ]; then
echo "Your Public DNS Server is Yandex (77.88.8.7,77.88.8.3), safe choice with Family Filter! "
fi
if [ $( head -n1 $CONF | awk '{print $5}') == "185.228.168.168,185.228.169.168" ]; then
echo "Your Public DNS Server is Clean Browsing (185.228.168.168,185.228.169.168), Uuh TLS encrypted safe choice with Family Filter and Youtube-Safe Option! "
fi
if [ $( head -n1 $CONF | awk '{print $5}') == "10.8.0.1" ]; then
echo "Nothing else then own encrypted and logless dedicated DNS Server! "
fi
;;
"Change your DNS Server")
if [ $( head -n1 $CONF | awk '{print $5}') == "1.1.1.1,1.0.0.1" ]; then
echo "Your Public DNS Server is Cloudflare (1.1.1.1,1.0.0.1), great unfiltered choice for best speed worldwide! "
fi
if [ $( head -n1 $CONF | awk '{print $5}') == "176.103.130.130,176.103.130.131" ]; then
echo "Your Public DNS Server is Adguard (176.103.130.130,176.103.130.131), Advertising Filter kill them all! "
fi
if [ $( head -n1 $CONF | awk '{print $5}') == "84.200.69.80,84.200.70.40" ]; then
echo "Your Public DNS Server is WATCH.DNS (84.200.69.80,84.200.70.40), great unfiltered choice for German Clients! "
fi
if [ $( head -n1 $CONF | awk '{print $5}') == "9.9.9.9, 149.112.112.112" ]; then
echo "Your Public DNS Server is QUAD9 (9.9.9.9, 149.112.112.112), great TLS encrypted unfiltered choice! "
fi
if [ $( head -n1 $CONF | awk '{print $5}') == "77.88.8.7,77.88.8.3" ]; then
echo "Your Public DNS Server is Yandex (77.88.8.7,77.88.8.3), safe choice with Family Filter! "
fi
if [ $( head -n1 $CONF | awk '{print $5}') == "185.228.168.168,185.228.169.168" ]; then
echo "Your want leave your Clean Browsing server and use another one?. You need generate new configs later, if you want to use new Server (Start Menu choice: 3 ) "
# client choice NEW DNS
read -rp "Do you really want to change your DNS Server? (y/n) " -e -i y NEW_DNS
if [ "$NEW_DNS" == "y" ]; then
echo "Which DNS do you want to use with the VPN?"
echo "You recognise encrypted DNS with "TLS" (Port 853 can be potentially blocked through Government etc.) Some Servers use logs, but no one of them log aWireguard IP. "
echo " 1) Cloudflare: log: yes 24h, Filter: no, + best speed worldwide"
echo " 2) AdGuard: Log: yes, Filter: advertising"
echo " 3) DNS.WATCH: Log: no, Filter: no, + great speed for Germany"
echo " 4) Quad9: TLS: yes, Log: yes, Filter: no"
echo " 5) Yandex Family: TLS:no, Log: yes, Filter: adult"
echo " 6) Clean Browsing Family: TLS: yes, Log: yes, Filter: adult and explicit sites, Youtube- safe mode"
read -p "DNS [1-6]: " -e -i 1 NEW_DNS
case $NEW_DNS in
1)
NEW_DNS="1.1.1.1,1.0.0.1"
;;
2)
NEW_DNS="176.103.130.130,176.103.130.131"
;;
3)
NEW_DNS="84.200.69.80,84.200.70.40"
;;
4)
NEW_DNS="9.9.9.9, 149.112.112.112"
;;
5)
NEW_DNS="77.88.8.7,77.88.8.3"
;;
6)
NEW_DNS="185.228.168.168,185.228.169.168"
;;
esac
fi
# EOF client choices DNS
fi
sed "s/185\.228\.168\.168,185\.228\.169\.168/$NEW_DNS/" /etc/wireguard/wg0.conf
if [ $( head -n1 $CONF | awk '{print $5}') == "10.8.0.1" ]; then
echo "Nothing else then own encrypted and logless dedicated DNS Server! "
fi
;;
"Install/add new Client")
break
;;
"Quit")
exit
;;
esac
done
|
If you want to replace that string itself with what you have in the variable:
sed "s|185\.228\.168\.168,185\.228\.169\.168|$NEW_DNS|" /etc/wireguard/wg0.conf
You need sed s|string|replacement|. You can use sed s|string|replacement|g to replace it throughout the file. You also need to escape . with a backslash so it doesn't represent a single character. I've removed the -i switch so that the changes are written to standard output so you can make sure that it's what you want. You can put it back into the command once you have confirmed that it is.
If you want to edit the file itself, add the -i switch to your command.
sed -i "s|185\.228\.168\.168,185\.228\.169\.168|$NEW_DNS|" /etc/wireguard/wg0.conf
| Sed escaping "." and use $variable? |
1,401,895,989,000 |
When I run ifconfig -a, I only get lo and enp0s10 interfaces, not the classical eth0
What does enp0s10 mean? Why is there no eth0?
|
That's a change in how now udevd assigns names to ethernet devices. Now your devices use the "Predictable Interface Names", which are based on (and quoting the sources):
Names incorporating Firmware/BIOS provided index numbers for on-board devices (example: eno1)
Names incorporating Firmware/BIOS provided PCI Express hotplug slot index numbers (example: ens1)
Names incorporating physical/geographical location of the connector of the hardware (example: enp2s0)
Names incorporating the interfaces's MAC address (example: enx78e7d1ea46da)
Classic, unpredictable kernel-native ethX naming (example: eth0)
The why's this changed is documented in the systemd freedesktop.org page, along with the method to disable this:
ln -s /dev/null /etc/udev/rules.d/80-net-setup-link.rules
or if you use older versions:
ln -s /dev/null /etc/udev/rules.d/80-net-name-slot.rules
| Why is my ethernet interface called enp0s10 instead of eth0? |
1,401,895,989,000 |
I have a Dell XPS 13 ultrabook which has a wifi nic, but no physical ethernet nic (wlan0, but no eth0). I need to create a virtual adapter for using Vagrant with NFS, but am finding that the typical ifup eth0:1... fails with ignoring unknown interface eth0:1=eth0:1. I also tried creating a virtual interface against wlan0, but received the same result.
How can I create a virtual interface on this machine with no physical interface?
|
Setting up a dummy interface
If you want to create network interfaces, but lack a physical NIC to back it, you can use the dummy link type. You can read more about them here: iproute2 Wikipedia page.
Creating eth10
To make this interface you'd first need to make sure that you have the dummy kernel module loaded. You can do this like so:
$ sudo lsmod | grep dummy
$ sudo modprobe dummy
$ sudo lsmod | grep dummy
dummy 12960 0
With the driver now loaded you can create what ever dummy network interfaces you like:
$ sudo ip link add eth10 type dummy
NOTE: In older versions of ip you'd do the above like this, appears to have changed along the way. Keeping this here for reference purposes, but based on feedback via comments, the above works now.
$ sudo ip link set name eth10 dev dummy0
And confirm it:
$ ip link show eth10
6: eth10: <BROADCAST,NOARP> mtu 1500 qdisc noop state DOWN mode DEFAULT group default
link/ether c6:ad:af:42:80:45 brd ff:ff:ff:ff:ff:ff
Changing the MAC
You can then change the MAC address if you like:
$ sudo ifconfig eth10 hw ether 00:22:22:ff:ff:ff
$ ip link show eth10
6: eth10: <BROADCAST,NOARP> mtu 1500 qdisc noop state DOWN mode DEFAULT group default
link/ether 00:22:22:ff:ff:ff brd ff:ff:ff:ff:ff:ff
Creating an alias
You can then create aliases on top of eth10.
$ sudo ip addr add 192.168.100.199/24 brd + dev eth10 label eth10:0
And confirm them like so:
$ ifconfig -a eth10
eth10: flags=130<BROADCAST,NOARP> mtu 1500
ether 00:22:22:ff:ff:ff txqueuelen 0 (Ethernet)
RX packets 0 bytes 0 (0.0 B)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 0 bytes 0 (0.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
$ ifconfig -a eth10:0
eth10:0: flags=130<BROADCAST,NOARP> mtu 1500
inet 192.168.100.199 netmask 255.255.255.0 broadcast 192.168.100.255
ether 00:22:22:ff:ff:ff txqueuelen 0 (Ethernet)
Or using ip:
$ ip a | grep -w inet
inet 127.0.0.1/8 scope host lo
inet 192.168.1.20/24 brd 192.168.1.255 scope global wlp3s0
inet 192.168.122.1/24 brd 192.168.122.255 scope global virbr0
inet 192.168.100.199/24 brd 192.168.100.255 scope global eth10:0
Removing all this?
If you want to unwind all this you can run these commands to do so:
$ sudo ip addr del 192.168.100.199/24 brd + dev eth10 label eth10:0
$ sudo ip link delete eth10 type dummy
$ sudo rmmod dummy
References
MiniTip: Setting IP Aliases under Fedora
Linux Networking: Dummy Interfaces and Virtual Bridges
ip-link man page
iproute2 HOWTO
iproute2 cheatsheet
| How can I create a virtual ethernet interface on a machine without a physical adapter? |
1,401,895,989,000 |
I am searching for an explanation what exactly the output of the commands ip link and ip addr means on a linux box.
# ip link
3: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP mode DEFAULT qlen 1000
link/ether 00:a1:ba:51:4c:11 brd ff:ff:ff:ff:ff:ff
4: eth1: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc pfifo_fast state DOWN mode DEFAULT qlen 1000
link/ether 00:a1:ba:51:4c:12 brd ff:ff:ff:ff:ff:ff
What exactly are the LOWER_UP, NO-CARRIER and other flags? I have found a reference at http://download.vikis.lt/doc/iproute-doc-2.6.32/ip-cref.ps but it does not contain complete information and man pages are not detailed enough.
|
Those are interface's flags. They are documented in the netdevice(7) man-page. Below is the relevant part (reordered alphabetically):
IFF_ALLMULTI Receive all multicast packets.
IFF_AUTOMEDIA Auto media selection active.
IFF_BROADCAST Valid broadcast address set.
IFF_DEBUG Internal debugging flag.
IFF_DORMANT Driver signals dormant (since Linux 2.6.17)
IFF_DYNAMIC The addresses are lost when the interface goes down.
IFF_ECHO Echo sent packets (since Linux 2.6.25)
IFF_LOOPBACK Interface is a loopback interface.
IFF_LOWER_UP Driver signals L1 up (since Linux 2.6.17)
IFF_MASTER Master of a load balancing bundle.
IFF_MULTICAST Supports multicast
IFF_NOARP No arp protocol, L2 destination address not set.
IFF_NOTRAILERS Avoid use of trailers.
IFF_POINTOPOINT Interface is a point-to-point link.
IFF_PORTSEL Is able to select media type via ifmap.
IFF_PROMISC Interface is in promiscuous mode.
IFF_RUNNING Resources allocated.
IFF_SLAVE Slave of a load balancing bundle.
IFF_UP Interface is running.
So, LOWER_UP means there is a signal at the physical level (i.e. something active is plugged in the network interface). NO-CARRIER, is the exact opposite: no signal is detected at the physical level.
| ip link and ip addr output meaning |
1,401,895,989,000 |
I am using Raspberry Pi using Raspbian which is just Debian.
I would like to bridge from the primary WiFi network router that connects to Cox Cable to my cabled router here for my subnet to have reliable internet access.
It needs to be a WiFi-to-Ethernet bridge.
I have set /etc/networks for a static address for the USB wlan1 with the external adapter and hi-gain antenna. wpa_supplicant is configured to log in to the master router properly.
So right now it is set up so I can login to the proper network with the password, on external wlan1. Static address is set in /etc/networks. Gateway and nameserver are OK. I can browse web pages, etc.
The missing link is to bridge this to the eth0 port so my router can connect also, to provide service to my subnet.
No need for any extra network services like routing or nat or dhcp, etc. Just a simple bridge.
Can anyone please point me in the right direction to make this happen?
|
For configuring a bridge from ethernet to wifi, it is as simple as doing in your /etc/network/interfaces:
auto eth0
allow-hotplug eth0
iface eth0 inet manual
auto wlan0
allow-hotplug wlan0
iface wlan0 inet manual
auto br0
iface br0 inet static
bridge_ports eth0 wlan0
address 192.168.1.100
netmask 255.255.255.0
Replace the IP address with something more appropriate to your network.
If you prefer the IP attribution done via DHCP, change it to:
auto br0
iface br0 inet dhcp
bridge_ports eth0 wlan0
After changing /etc/network/interfaces, either restarting Debian or doing
service networking restart
Will activate this configuration.
You will have to make sure for this configuration to have bridge-utils installed. You can install it with:
sudo apt install bridge-utils
For more information, see:
BRIDGE-UTILS-INTERFACES
The wlan0 interface also has to be condigured to connect to your remote AP so this configuration is not be used verbatim.
Additional note: bridging eth0 and wlan0 together means in poor layman´s terms that br0 will present itself as a single logical interface englobing the interfaces that make part of the bridge. Usually such configuration is made when both extend or belong to the same network.
| How do I configure a network interface bridge from WiFi to Ethernet with Debian? |
1,401,895,989,000 |
I have two computer, both with linux, which are currently connected to a router/switch via a 1000Mb/s ethernet port (installed in mb).
This allows me to transfer data at max 120MB/s between two hosts.
As I need to increase this speed, would it be possible to install two 2.5Gb ethernet card in the two PCIe slots of both motherboard (total of 4 new ethernet card), connect them directly with 2 cables (not passing via router/switch), and make both cards to be seen as one logical network interface with a theoretical speed of 5Gb ?
How would I do that?
Also, I see single ethernet cards (PCIx) with two RJ45 port; can these 2 ports be used at full speed at the same time?
|
Yes, it is possible.
You, most likely, would need to install "link bonding driver". A driver which would balance and synchronize packets sent over two (or more) links. It is not a part of default setup in most distributions, but available in repositories. For Ubuntu family, for example, you can get a nice instruction here: https://help.ubuntu.com/community/UbuntuBonding
You can also google words "link aggregation" or "link teaming". While this approach to connection speed and sustainability is used a lot on server side, we still do not have a single term for it...
| Can I use two ethernet card to increase transfer speed between two linux OS in lan? |
1,401,895,989,000 |
In the following example:
$ ip a | grep scope.global
inet 147.202.85.48/24 brd 147.202.85.255 scope global dynamic enp0s3
What does the 'brd' mean?
|
brd is short for broadcast.
147.202.85.255 is the broadcast address for whatever interface that line belongs to.
| meaning of "brd" in output of IP commands |
1,401,895,989,000 |
I am running KVM on RHEL6, and I have created several virtual machines in it. Issuing ifconfig command to the host system command line shows a list of virbr0, virbr1... and vnet0, vnet2... Are they the IP addresses of the the guest OS? What are the differences between virbr# and vnet#?
|
Those are network interfaces, not IP addresses. A network interface can have packets from any protocol exchanged on them, including IPv4 or IPv6, in which case they can be given one or more IP addresses.
virbr are bridge interfaces. They are virtual in that there's no network interface card associated to them. Their role is to act like a real bridge or switch, that is switch packets (at layer 2) between the interfaces (real or other) that are attached to it just like a real ethernet switch would.
You can assign an IP address to that device, which basically gives the host an IP address on that subnet which the bridge connects to. It will then use the MAC address of one of the interfaces attached to the bridge.
The fact that their name starts with vir doesn't make them any different from any other bridge interface, it's just that those have been created by libvirt which reserves that name space for bridge interfaces
vnet interfaces are other types of virtual interfaces called tap interfaces. They are attached to a process (in this case the process runnin the qemu-kvm emulator). What the process writes to that interface will appear as having been received on that interface by the host and what the host transmits on that interface is available for reading by that process. qemu typically uses it for its virtualized network interface in the guest.
Typically, a vnet will be added to a bridge interface which means plugging the VM into a switch.
| What is the difference between virbr# and vnet#? |
1,401,895,989,000 |
I'm trying to set up a system that joins an untagged Ethernet network to a TAP tunnel, adding a VLAN tag as the traffic moves to the tunnel.
So far I have:
eth0 - the physical Ethernet interface carrying untagged traffic.
tap1 - the TAP tunnel interface.
br0 - a bridge that contains tap1 (and some other physical interfaces)
I know I can add a VLAN tag on the Ethernet side by doing this:
$ ip link add link eth0 name eth0.5 type vlan id 5
$ brctl addif br0 eth0.5
But how can I do the reverse?
Edit I've figured out I can do this:
$ ip link add veth0 type veth peer name veth1
$ ip link add link veth0 name veth0.5 type vlan id 5
$ brctl addif br0 veth0.5
$ brctl addbr br1
$ brctl addif br1 eth0
$ brctl addif br1 veth1
I think this does what I want - it creates two bridges, with a virtual ethernet device connecting them, and adds/removes the VLAN tag as the traffic passes between the bridges. Is there anything simpler?
|
Yes: you can set the bridge to be VLAN aware.
The bridge will then handle VLAN IDs attached to frames crossing it, including tagging and untagging them according to configuration, and will send a frame belonging to a given VLAN only to ports configured to accept it. This moves all the settings to the bridge itself rather than having to use VLAN sub interfaces (those sub interfaces can still be used in some settings of course).
This feature is not available through the obsolete brctl command, but requires the newer replacement bridge command (along with the usual ip link command). It is a simpler setup (one bridge, no sub-interface).
The method is to configure tap1 as a tagged bridge port with VLAN ID (VID) 5, and eth0 also with VID 5, but set as untagged: output gets untagged, and with this VID as PVID (Port VLAN ID): input gets tagged with it inside the bridge. There can be only one PVID per port.
At the same time optionally remove VLAN ID of 1 assigned by default to each port (unless a more complex setup would require multiple VLANs of course) to keep a clean configuration.
your setup, so far, with newer commands only should look like this:
ip link set eth0 up
ip link set tap1 up
# the following line could have directly included at bridge creation the additional parameter `vlan_filtering 1`
ip link add name br0 type bridge
ip link set tap1 master br0
ip link set eth0 master br0
The specific VLAN aware bridge settings, starting by activating the feature:
ip link set dev br0 type bridge vlan_filtering 1
bridge vlan del dev tap1 vid 1
bridge vlan del dev eth0 vid 1
bridge vlan add dev tap1 vid 5
bridge vlan add dev eth0 vid 5 pvid untagged
ip link set br0 up
Note that the bridge's self implicit port is still using VID 1, so assigning an IP directly on the bridge as is done on some settings will now fail to communicate properly. If such configuration is really needed, you can set the bridge's self port in VLAN 5 too, with a slightly different syntax (self) because it's the bridge itself:
bridge vlan del dev br0 vid 1 self
bridge vlan add dev br0 vid 5 pvid untagged self
It's usually cleaner to (still delete the default VID 1 of the bridge to prevent it from any possible interaction,) add a veth pair, plug one end on the bridge, configure its bridge vlan settings the same as eth0 and assign an IP on the other end.
Good blog series on this topic:
Fun with veth-devices, Linux bridges and VLANs in unnamed Linux
network namespaces
I II III IV V VI VII VIII
| Bridged interfaces and VLAN tags |
1,401,895,989,000 |
On my wired LAN, with 1GBit/s devices, I have two Linux machines (One Haswell, One Skylake Xeon) and when I do a secure copy of a large file, I see 38MB/s.
Seeing that this is 3 times below the 1000Mbit/s spec, I wonder if this performance is as expected?
Both machines use SSD for storage, both run 64bit Ubuntu.
During the transfer, both machine have approximately one core at 30% load.
The router that sits between the machines is a TP-Link Archer C7 AC1750. Both machines have Intel(R) Gigabit Ethernet Network devices that are in Full Duplex mode.
What is a normal scp transfer speed on 1Gbit LANs?
UPDATE
Using /dev/zero to rule out disk IO yielded the same results.
Using nc yielded slightly higher: 41MiB/s.
Paradoxically, UDP nc was slower than TCP nc, at 38MiB/s?
Switching to crossover cable: 112MB/s for scp.
CONCLUSION
The TP-Link router in between was the weak link in the network, and could not keep up.
|
It does seem slow from a theoretical stand point although I've not seen any transfers much quicker practically on home hardware.
Some experiments you might like to try to rule out possible limiting factors:
Assess your raw SSH speed by copying from /dev/zero to /dev/null. This rules out a HD bottle neck.
ssh remote_host cat /dev/zero | pv > /dev/null
Check other unencrypted protocols such as HTTP. HTTP actually sends files as with nothing but a header. Sending large files over HTTP is a reasonable measure of TCP speeds.
Check that you are not forcing traffic through the router but only it's ethernet switch. For example if your machine has a public IP and local IP, then scp to/from the local IP. This is because home routers often have to process WAN traffic through their CPU which creates a bottle neck. Even if both machines are on the LAN, using the public IP can force packets through the CPU as if it was going to the WAN.
Similarly I would use IPv4. Some home routers have a weird behaviour with IPv6 where they ask all local traffic to be forwarded to the router.
If at all possible try with a gigabit crossover cable instead of a router. This should rule out router.
| scp performance over 1Gbit LAN |
1,401,895,989,000 |
I have a device that I need to connect to over SSH. The device is connected to my workstation via a direct ethernet connection. I'm attempting to assign the connected device an IP address somehow that I can SSH to, however all of the guides I'm finding have the user configure the IP from whatever device they're working with (namely Raspberry Pi's and so on). This is not something I can do with this device as I've no physical interface to work with.
I've been recommended to setup a DHCP server on my workstation so it would take care of this for me, however I've no idea how to configure it and none of the guides I have followed have been helpful. With that approach, I seem to have been able to bind an IP to the interface the device is connected on, however SSHing to that IP just brings me back to my own machine.
So my main question is: How do I assign an IP address to a device directly connected to my computer via ethernet cable without having any kind of access to the device (no interface, keyboard, monitor, etc). If the answer is to set up a DHCP server on my machine, how do I properly configure this and get an IP I can SSH to?
For reference, I am using Ubuntu 16.04 with OpenSSH installed. The device is also running some flavor of Linux and has SSH software installed, but again there's no way to interact with it except through SSH. I also do not have access to my router, so plugging the device in there and letting the router do the work is not an option.
|
The link given by @steve as a comment is appropriate, but if you want to try something simple first just to see what the device does you can use dnsmasq, which is a simple dns and dhcp server. Install with sudo apt-get install dnsmasq. If this also enables and starts the server you need to stop and disable it.
If, say, your device is on your ethernet interface eth2, and you have done sudo ifconfig eth2 192.168.9.1 to set the interface ip address, then you can try:
sudo dnsmasq -d -C /dev/null --port=0 --domain=localdomain --interface=eth2 --dhcp-range=192.168.9.2,192.168.9.10,99h
which sets up a dhcp server in debug mode (-d), not as a daemon, with dns (port=0) able to offer addresses in the range .2 to .10, and to hold the same ones for 99hours.
If your device broadcasts a request to discover an address you should see it, and the reply (offer):
dnsmasq-dhcp: DHCPDISCOVER(eth2) 94:71:ac:ff:85:9d
dnsmasq-dhcp: DHCPOFFER(eth2) 192.168.9.2 94:71:ac:ff:85:9d
The numbers are the ip address assigned and the device's mac address. You may need to reset or power on the device if it has given up broadcasting. The device might reply to ping 192.168.9.2 and then you can try to ssh too.
You can interrupt the dnsmasq once the address has been offered in this test and put the options in the standard dnsmasq config file and so on.
You may also usefully run sudo tcpdump -i eth2 to see what packets pass.
| How to connect to device via SSH over direct ethernet connection |
1,401,895,989,000 |
I am running Arch Linux (on a Raspberry Pi 3) and tried to connect both the Ethernet and the Wi-Fi to the same network. route shows me the following:
$ route
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
default gateway 0.0.0.0 UG 1024 0 0 eth0
default gateway 0.0.0.0 UG 1024 0 0 wlan0
192.168.1.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0
192.168.1.0 0.0.0.0 255.255.255.0 U 0 0 0 wlan0
gateway 0.0.0.0 255.255.255.255 UH 1024 0 0 eth0
gateway 0.0.0.0 255.255.255.255 UH 1024 0 0 wlan0
ip addr shows me the following:
$ ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
link/ether b8:27:XX:XX:XX:XX brd ff:ff:ff:ff:ff:ff
inet 192.168.1.103/24 brd 192.168.1.255 scope global dynamic eth0
valid_lft 85717sec preferred_lft 85717sec
inet6 fe80::ba27:ebff:fee4:4f60/64 scope link
valid_lft forever preferred_lft forever
3: wlan0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
link/ether b8:27:YY:YY:YY:YY brd ff:ff:ff:ff:ff:ff
inet 192.168.1.102/24 brd 192.168.1.255 scope global dynamic wlan0
valid_lft 85727sec preferred_lft 85727sec
inet6 fe80::ba27:ebff:feb1:1a35/64 scope link
valid_lft forever preferred_lft forever
Both wlan0 and eth0 interfaces were able to get an IP address from the router.
But it turns out that only one of these interfaces ever works. The other interface cannot be pinged and is not connectable. Usually it's the Ethernet that works but sometimes it's the Wi-Fi.
What's happening? What can I do to make this work?
|
As you have found out, from the routing perspective, while possible, it is not ideal to have addresses from the same network in different interfaces.
Routing expects a different network per interface, and ultimately one of them will take precedence over the other in routing, since they overlap.
The advised solution for having more than one interface connected to the same network is to aggregate them together in a bridge interface.
The bridge interface will "own" the IP address, and the actual real interfaces are grouped as a virtual single entity under br0.
allow-hotplug eth0
iface eth0 inet manual
allow-hotplug wlan0
iface wlan0 inet manual
auto br0
iface br0 inet dhcp
bridge_ports eth0 wlan0
Debian Linux: Configure Network Interfaces As A Bridge / Network Switch
| Possible to have both Wi-Fi and Ethernet connected to the same network? |
1,401,895,989,000 |
As I was trying in vain to fix a faulty ethernet controller here, one thing I tried was running tcpdump on the machine.
I found it interesting that tcpdump was able to detect that some of the ICMP packets the ping application thought it was sending were not actually going out on the wire, even though it was running on the same machine. I have reproduced those tcpdump results here:
14:25:01.162331 IP debian.local > 74.125.224.80: ICMP echo request, id 2334, seq 1, length 64
14:25:02.168630 IP debian.local > 74.125.224.80: ICMP echo request, id 2334, seq 2, length 64
14:25:02.228192 IP 74.125.224.80 > debian.local: ICMP echo reply, id 2334, seq 2, length 64
14:25:07.236359 IP debian.local > 74.125.224.80: ICMP echo request, id 2334, seq 3, length 64
14:25:07.259431 IP 74.125.224.80 > debian.local: ICMP echo reply, id 2334, seq 3, length 64
14:25:31.307707 IP debian.local > 74.125.224.80: ICMP echo request, id 2334, seq 9, length 64
14:25:32.316628 IP debian.local > 74.125.224.80: ICMP echo request, id 2334, seq 10, length 64
14:25:33.324623 IP debian.local > 74.125.224.80: ICMP echo request, id 2334, seq 11, length 64
14:25:33.349896 IP 74.125.224.80 > debian.local: ICMP echo reply, id 2334, seq 11, length 64
14:25:43.368625 IP debian.local > 74.125.224.80: ICMP echo request, id 2334, seq 17, length 64
14:25:43.394590 IP 74.125.224.80 > debian.local: ICMP echo reply, id 2334, seq 17, length 64
14:26:18.518391 IP debian.local > 74.125.224.80: ICMP echo request, id 2334, seq 30, length 64
14:26:18.537866 IP 74.125.224.80 > debian.local: ICMP echo reply, id 2334, seq 30, length 64
14:26:19.519554 IP debian.local > 74.125.224.80: ICMP echo request, id 2334, seq 31, length 64
14:26:20.518588 IP debian.local > 74.125.224.80: ICMP echo request, id 2334, seq 32, length 64
14:26:21.518559 IP debian.local > 74.125.224.80: ICMP echo request, id 2334, seq 33, length 64
14:26:21.538623 IP 74.125.224.80 > debian.local: ICMP echo reply, id 2334, seq 33, length 64
14:26:37.573641 IP debian.local > 74.125.224.80: ICMP echo request, id 2334, seq 35, length 64
14:26:38.580648 IP debian.local > 74.125.224.80: ICMP echo request, id 2334, seq 36, length 64
14:26:38.602195 IP 74.125.224.80 > debian.local: ICMP echo reply, id 2334, seq 36, length 64
Notice how the seq number jumps several times... that indicates packets the ping application generates that are not actually leaving the box.
Which brings me to my question: how was tcpdump able to detect that the ICMP packets weren't actually going out? Is it able to somehow directly monitor what is on the wire?
If it does accomplish this, I assume it is by interfacing to some part of the kernel, which in turn interfaces to some hardware that is a standard part of a network controller.
Even so, that's pretty cool! If that is not actually how tcpdump functions, can someone explain to me how it detected the missing packets in software?
|
Yes. By putting network interfaces into promiscuous mode, tcpdump is able to see exactly what is going out (and in) the network interface.
tcpdump operates at layer2 +. it can be used to look at Ethernet, FDDI, PPP & SLIP, Token Ring, and any other protocol supported by libpcap, which does all of tcpdump's heavy lifting.
Have a look at the pcap_datalink() section of the pcap man page for a complete list of the layer 2 protocols that tcpdump (via libpcap) can analyze.
A read of the tcpdump man page will give you a good understanding of how exactly, tcpdump and libpcap interface with the kernel and network interfaces to be able to read the raw data link layer frames.
| what level of the network stack does tcpdump get its info from? |
1,401,895,989,000 |
In Linux, is there any difference between after-ip link down-condition and real link absence (e.g. the switch's port burned down, or someone tripped over a wire).
By difference I mean some signs in the system that can be used to distinguish these two conditions.
E.g. will routing table be identical in these two cases? Will ethtool or something else show the same things? Is there some tool/utility which can distinguish these conditions?
|
There are difference between an interface which is administratively up but disconnected or administratively down.
Disconnected
The interface gets a carrier down status. Its proper handling might depend on the driver for the interface and the kernel version. Normally it's available with ip link show. For example with a virtual ethernet veth interface:
# ip link add name vetha up type veth peer name vethb
# ip link show type veth
2: vethb@vetha: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN mode DEFAULT group default qlen 1000
link/ether 02:a0:3b:9a:ad:4d brd ff:ff:ff:ff:ff:ff
3: vetha@vethb: <NO-CARRIER,BROADCAST,MULTICAST,UP,M-DOWN> mtu 1500 qdisc noqueue state LOWERLAYERDOWN mode DEFAULT group default qlen 1000
link/ether 36:e3:62:1b:a8:1f brd ff:ff:ff:ff:ff:ff
vetha which is itself administratively UP, displays NO-CARRIER and the equivalent operstate LOWERLAYERDOWN flags: it's disconnected.
Equivalent /sys/ entries exist too:
# cat /sys/class/net/vetha/carrier /sys/class/net/vetha/operstate
0
lowerlayerdown
In usual settings, for an interface which is administratively up the carrier and operstate match (NO-CARRIER <=> LOWERLAYERDOWN or LOWER_UP <=> UP). One exception would be for example when using IEEE 802.1X authentication (advanced details of operstate are described in this kernel documentation: Operational States, but it's not needed for this explanation).
ethtool queries a lower level API to retrieve this same carrier status.
Having no carrier doesn't prevent any layer 3 settings to stay in effect. The kernel doesn't change addresses or routes when this happens. It's just that in the end a packet that should be emitted won't be emitted by the interface and of course no reply will come either. So for example trying to connect to an other IPv4 address will sooner or later trigger again an ARP request which will fail, and the application will receive a "No route to host". Established TCP connections will just bid their time and stay established.
Administratively down
Above vethb has operstate DOWN and doesn't display any carrier status (since it has to be up to detect this. A physical Ethernet interface of course behaves the same).
When the interface is brought down (ip link set ... down), the carrier can't be detected anymore since the underlying hardware device was very possibly powered off and the operstate becomes "down". ethtool will just say there's no link too, so can't be used reliably for this (it will surely display a few unknown entries too but is there a reliable scheme for this?).
This time this will have an effect on layer 3 network settings. The kernel will refuse to add routes using this interface and will remove any previous routes related to it:
the automatic (proto kernel) LAN routes added when adding an address
any other route added (eg: the default route) in any routing table (not only the main routing table) depending directly on the interface (scope link) or on other previous deleted routes (probably then scope global) . As these won't reappear when the interface is brought back up (ip link set ... up) they are lost until an userspace tool adds them back.
Userspace interactions
When using recent tools like NetworkManager, one can get confused and think a disconnect is similar to an interface down. That's because NM monitors links and will do actions when such events happen. To get an idea the ip monitor tool can be used to monitor from scripts, but it doesn't have a stable/parsable output currently (no JSON output available), so its use gets limited.
So when a wire is disconnected, NM will very likely consider it's not using the current configuration anymore unless a specific setting prevents it: it will then delete the addresses and routes itself. When the wire is connected back, NM will apply its configuration again: adds back addresses and routes (using DHCP if relevant). This looks like the same but isn't. All this time the interface stayed up, or it wouldn't even have been possible for NM to be warned when the connection was back.
Summary
It's easy to distinguish the two cases: ip link show will display NO-CARRIER+LOWERLAYERDOWN for a disconnected interface, and DOWN for an interface administratively brought down.
setting an interface administratively down (and up) can lose routes
losing carrier and recovering it doesn't disrupt network settings. If the delay is short enough it should not even disrupt ongoing network connections
but applications managing network might react and change network settings, sometimes with a result similar to administratively down case
you can use commands like ip monitor link to receive events about interfaces set administratively down/up or carrier changes, or ip monitor to receive all the multiple related events (including address or route changes) that would happen at this time or shortly after.
Most ip commands (but not ip monitor) have a JSON output available with ip -json ... to help scripts (along with jq).
Example (continuing from the first veth example):
vethb is still down:
# ip -j link show dev vethb | jq '.[].operstate'
"DOWN"
# ip -j link show dev vetha | jq '.[].operstate'
"LOWERLAYERDOWN"
Set vethb up, which now gets a carrier on both:
# ip link set vethb up
# ip -j link show dev vetha | jq '.[].operstate'
"UP"
This tells about the 3 usual states: administratively down, lowerlayerdown (ie: up but disconnected) or up (ie: operational).
| The difference between ip link down and physical link absence |
1,401,895,989,000 |
I have a debian linux box (Debian Squeeze) that deadlocks every few hours if I run a python script that sniffs an interface...
The stack trace is attached to the bottom of this question. Essentially, I have a Broadcom ethernet interface (bnx2 driver) that seems to die when I start a sniffing session and then it tries to transmit a frame out the same interface.
From what I can tell, a kernel watchdog timer is tripping...
NETDEV WATCHDOG: eth3 (bnx2): transmit queue 0 timed out
I think there is a way to control watchdog timers with ioctl (ref: EmbeddedFreak: How to use linux watchdog).
Questions (Original):
How can I find which watchdog timer(s) is controlling eth3? Bonus points if you can tell me how to change the timer or even disable the watchdog...
Questions (Revised):
How can I prevent the ethernet watchdog timer from causing problems?
Stack trace
Apr 30 08:38:44 Hotcoffee kernel: [275460.837147] ------------[ cut here ]------------
Apr 30 08:38:44 Hotcoffee kernel: [275460.837166] WARNING: at /build/buildd-linux-2.6_2.6.32-41squeeze2-amd64-NDo8b7/linux-2.6-2.6.32/debian/build/source_amd64_none/net/sched/sch_generic.c:261 dev_watchdog+0xe2/0x194()
Apr 30 08:38:44 Hotcoffee kernel: [275460.837169] Hardware name: PowerEdge R710
Apr 30 08:38:44 Hotcoffee kernel: [275460.837171] NETDEV WATCHDOG: eth3 (bnx2): transmit queue 0 timed out
Apr 30 08:38:44 Hotcoffee kernel: [275460.837172] Modules linked in: 8021q garp stp parport_pc ppdev lp parport pci_stub vboxpci vboxnetadp vboxnetflt vboxdrv ext2 loop psmouse power_meter button dcdbas evdev pcspkr processor serio_raw ext4 mbcache jbd2 crc16 sg sr_mod cdrom ses ata_generic sd_mod usbhid hid crc_t10dif enclosure uhci_hcd ehci_hcd megaraid_sas ata_piix thermal libata usbcore nls_base scsi_mod bnx2 thermal_sys [last unloaded: scsi_wait_scan]
Apr 30 08:38:44 Hotcoffee kernel: [275460.837202] Pid: 0, comm: swapper Not tainted 2.6.32-5-amd64 #1
Apr 30 08:38:44 Hotcoffee kernel: [275460.837204] Call Trace:
Apr 30 08:38:44 Hotcoffee kernel: [275460.837206] <IRQ> [<ffffffff81263086>] ? dev_watchdog+0xe2/0x194
Apr 30 08:38:44 Hotcoffee kernel: [275460.837211] [<ffffffff81263086>] ? dev_watchdog+0xe2/0x194
Apr 30 08:38:44 Hotcoffee kernel: [275460.837217] [<ffffffff8104df9c>] ? warn_slowpath_common+0x77/0xa3
Apr 30 08:38:44 Hotcoffee kernel: [275460.837220] [<ffffffff81262fa4>] ? dev_watchdog+0x0/0x194
Apr 30 08:38:44 Hotcoffee kernel: [275460.837223] [<ffffffff8104e024>] ? warn_slowpath_fmt+0x51/0x59
Apr 30 08:38:44 Hotcoffee kernel: [275460.837228] [<ffffffff8104a4ba>] ? try_to_wake_up+0x289/0x29b
Apr 30 08:38:44 Hotcoffee kernel: [275460.837231] [<ffffffff81262f78>] ? netif_tx_lock+0x3d/0x69
Apr 30 08:38:44 Hotcoffee kernel: [275460.837237] [<ffffffff8124dda3>] ? netdev_drivername+0x3b/0x40
Apr 30 08:38:44 Hotcoffee kernel: [275460.837240] [<ffffffff81263086>] ? dev_watchdog+0xe2/0x194
Apr 30 08:38:44 Hotcoffee kernel: [275460.837242] [<ffffffff8103fa2a>] ? __wake_up+0x30/0x44
Apr 30 08:38:44 Hotcoffee kernel: [275460.837249] [<ffffffff8105a71b>] ? run_timer_softirq+0x1c9/0x268
Apr 30 08:38:44 Hotcoffee kernel: [275460.837252] [<ffffffff81053dc7>] ? __do_softirq+0xdd/0x1a6
Apr 30 08:38:44 Hotcoffee kernel: [275460.837257] [<ffffffff8102462a>] ? lapic_next_event+0x18/0x1d
Apr 30 08:38:44 Hotcoffee kernel: [275460.837262] [<ffffffff81011cac>] ? call_softirq+0x1c/0x30
Apr 30 08:38:44 Hotcoffee kernel: [275460.837265] [<ffffffff8101322b>] ? do_softirq+0x3f/0x7c
Apr 30 08:38:44 Hotcoffee kernel: [275460.837267] [<ffffffff81053c37>] ? irq_exit+0x36/0x76
Apr 30 08:38:44 Hotcoffee kernel: [275460.837270] [<ffffffff810250f8>] ? smp_apic_timer_interrupt+0x87/0x95
Apr 30 08:38:44 Hotcoffee kernel: [275460.837273] [<ffffffff81011673>] ? apic_timer_interrupt+0x13/0x20
Apr 30 08:38:44 Hotcoffee kernel: [275460.837274] <EOI> [<ffffffffa01bc509>] ? acpi_idle_enter_bm+0x27d/0x2af [processor]
Apr 30 08:38:44 Hotcoffee kernel: [275460.837283] [<ffffffffa01bc502>] ? acpi_idle_enter_bm+0x276/0x2af [processor]
Apr 30 08:38:44 Hotcoffee kernel: [275460.837289] [<ffffffff8123a0ba>] ? cpuidle_idle_call+0x94/0xee
Apr 30 08:38:44 Hotcoffee kernel: [275460.837293] [<ffffffff8100fe97>] ? cpu_idle+0xa2/0xda
Apr 30 08:38:44 Hotcoffee kernel: [275460.837297] [<ffffffff8151c140>] ? early_idt_handler+0x0/0x71
Apr 30 08:38:44 Hotcoffee kernel: [275460.837301] [<ffffffff8151ccdd>] ? start_kernel+0x3dc/0x3e8
Apr 30 08:38:44 Hotcoffee kernel: [275460.837304] [<ffffffff8151c3b7>] ? x86_64_start_kernel+0xf9/0x106
Apr 30 08:38:44 Hotcoffee kernel: [275460.837306] ---[ end trace 92c65e52c9e327ec ]---
|
Commenting out my code that called ethtool to modify the NIC buffers stopped watchdog timers from tripping on the bnx2 card.
I still want to find an answer to the question about watchdog timers, but I will ask another question
def _linux_buffer_alloc(iface=None, rx_ring_buffers=768,
netdev_max_backlog=30000):
default_rx = 255
default_rx_jumbo = 0
default_netdev_max_backlog = 1000
## Set linux rx ring buffers (to prevent tcpdump 'dropped by intf' msg)
## FIXME: removing for now due to systematic deadlocks with the bnx2 driver
# sample: ethtool -G eth3 rx 768
# cmd = 'ethtool -G %s rx %s' % (iface, rx_ring_buffers)
# p = Popen(cmd.split(' '), stdout=PIPE)
# p.communicate(); time.sleep(0.15)
# sample: ethtool -G eth3 rx-jumbo 0
# cmd = 'ethtool -G %s rx-jumbo %s' % (iface, default_rx_jumbo)
# p = Popen(cmd.split(' '), stdout=PIPE)
# p.communicate(); time.sleep(0.15)
## /FIXME
| Solving Ethernet watchdog timer deadlocks |
1,401,895,989,000 |
Given a Linux server with an ethernet card, another device say an unconfigured router is connected with a patch lead (or an ethernet lead cabled in a different way if needed).
They're both powered up. Is there a way on the linux box to get the MAC address of the other device? There's no IP network going on here just two connected ethernet interfaces.
EDIT: The devices that this is concerning come with base config expecting to get an IP off a DHCP server which I can run on the linux host and work off that as soon as they get their temp IP.
|
If I'm not mistaken, ARP could be used to receive a MAC address of a machine. If you are connected at the data-link layer, I believe you can execute arp -an on a Linux machine to retrieve the MAC addresses of connected devices.
I've only used it to retrieve the MAC address associated with IP addresses, as that's what its usual function is - however due to the connectivity being over layer two, and that it uses the Ethernet broadcast address (FFFF.FFFF.FFFF), it should hopefully be able to retrieve the MAC address alone without an associated IP address.
I'm not actually able to test the above theory, but please let me know if you have any luck.
| Get MAC address of a directly connected device |
1,401,895,989,000 |
I recently noticed I am only getting 100Mbit/s of througput on my gigabit home network.
When looking into it with ethtool I found my ArchLinux Box was using 100baseT/Half as link speed instead of 1000baseT/Full which its NIC and the switch connected to it support.I am not sure why but the NIC seems to not be advertising its link-modes according to ethtool:
Settings for enp0s31f6:
Supported ports: [ TP ]
Supported link modes: 10baseT/Half 10baseT/Full
100baseT/Half 100baseT/Full
1000baseT/Full
Supported pause frame use: No
Supports auto-negotiation: Yes
Advertised link modes: Not reported
Advertised pause frame use: No
Advertised auto-negotiation: No
Speed: 100Mb/s
Duplex: Half
Port: Twisted Pair
PHYAD: 1
Transceiver: internal
Auto-negotiation: off
MDI-X: on (auto)
Supports Wake-on: pumbg
Wake-on: g
Current message level: 0x00000007 (7)
drv probe link
Link detected: yes
When enabling auto-negotioation explicitly by running ethtool --change enp0s31f6 autoneg on it seems to advertise all its modes to the switch and uses 1000baseT/Full.
That only works most of the time and for a while though. When I unplug the cable and pluggin it back in switches autoneg off most of the time, but not always. Also, sometimes setting autoneg to on immediately disables it again.
Rebooting also disables it again.
Note that auto-negotiation does not get disabled when unplugging but when replugging. dsmeg logs this when autoneg was enabled and I plug in a cable:
[153692.029252] e1000e: enp0s31f6 NIC Link is Up 1000 Mbps Full Duplex, Flow Control: Rx/Tx
[153699.577779] e1000e: enp0s31f6 NIC Link is Up 100 Mbps Half Duplex, Flow Control: None
[153699.577782] e1000e 0000:00:1f.6 enp0s31f6: 10/100 speed: disabling TSO
I am using the intel NIC of my asrock motherboard (from ~2015) and an unmanaged switch (Netgear GS208).
|
After hours of searching I found the solution in the most obvious place:
NetworkManager seems to somehow have disabled autonegotiation right in the settings for my ethernet port:
The weird part is that even after knowing NetworkManager can change the ethernet link-mode I cannot find even a single source online detailing that functionality. The only way according to the google search results I found is setting it via ethtool.
| Linux disables ethernet auto-negotiation on plugging-in the cable? |
1,401,895,989,000 |
I am trying to identify NICs on ~20 remote servers (2-6 NICs on every server). To begin with, I want to identify those ready for use and free ones. How can I check the state of the physical media? I know some ways, including ifconfig|grep RUNNING, ethtool, cat /sys/class/net/eth0/carrier, but all they require that the interface is up. I don't want to bring ALL interfaces up. Not sure why, but I don't like to have enabled, but not configured interfaces in the network. Is there a way I can avoid this?
Or am I just wrong and there's nothing bad about all interfaces being up (and not configured)? Even if they are plugged in?
|
ip link show , by default shows all the interfaces, use ip link show up to show only the running interfaces. You could use filters to get the difference.
| Check whether network cable is plugged in without bringing interface up |
1,401,895,989,000 |
Today I removed my GPU out of an Linux (Ubuntu) machine, and after that the ethernet stopped working. Running 'service networking restart' threw an error message, and when I ran 'ifconfig' only the local loopback was visible. After this I re-installed my GPU and out of nowhere the internet started working again??
I would really like to have my machine be able to access the internet without having to install a GPU in it..
The GPU installed is an NVIDIA GeForce GTX 750 Ti, and I'm using the onboard ethernet connector. If you need any more specifications, please tell me and I'll dig a bit further.
The output of ip link WITH a GPU:
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT group default qlen 1
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
2: enp2s0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP mode DEFAULT group default qlen 1000
link/ether d0:50:99:2f:ad:4d brd ff:ff:ff:ff:ff:ff
And without a GPU:
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT group default qlen 1
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
2: enp1s0: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN mode DEFAULT group default qlen 1000
link/ether d0:50:99:2f:ad:4d brd ff:ff:ff:ff:ff:ff
|
Your networking devices are renamed to correspond with their location on the PCI bus. When you removed your GPU, your ethernet device changed from enp2s0 to enp1s0.
In order to reconnect, you have a few options:
Create profiles for enp1s0 that match those of enp2s0
Change the rules for naming devices to give this card a unique name, and edit your profiles accordingly
See if swapping the positions of the network card and GPU make the network card always appear as enp1s0, and if so, edit the profiles to use that name
| Internet not working without gpu installed? |
1,401,895,989,000 |
How can I disable my Wifi radio when I've connected to a network via Ethernet (wired), but enable the Wifi connection if I don't have a wired connection? Essentially, I want XOR switch for my wired/wireless connection states.
|
I found a script by Ilija Matoski to accomplish exactly this, which would belong in /etc/NetworkManager/dispatcher.d/70-wifi-wired-exclusive.sh.
#!/bin/sh
name_tag="wifi-wired-exclusive"
syslog_tag="$name_tag"
skip_filename="/etc/NetworkManager/.$name_tag"
if [ -f "$skip_filename" ]; then
exit 0
fi
interface="$1"
iface_mode="$2"
iface_type=$(nmcli dev | grep "$interface" | tr -s ' ' | cut -d' ' -f2)
iface_state=$(nmcli dev | grep "$interface" | tr -s ' ' | cut -d' ' -f3)
logger -i -t "$syslog_tag" "Interface: $interface = $iface_state ($iface_type) is $iface_mode"
enable_wifi() {
logger -i -t "$syslog_tag" "Interface $interface ($iface_type) is down, enabling wifi ..."
nmcli radio wifi on
}
disable_wifi() {
logger -i -t "$syslog_tag" "Disabling wifi, ethernet connection detected."
nmcli radio wifi off
}
if [ "$iface_type" = "ethernet" ] && [ "$iface_mode" = "down" ]; then
enable_wifi
elif [ "$iface_type" = "ethernet" ] && [ "$iface_mode" = "up" ] && [ "$iface_state" = "connected" ]; then
disable_wifi
fi
Additionally, to disable this switching operation, you can create the file /etc/NetworkManager/.wifi-wired-exclusive (e.g. via touch).
| Disable Wifi on Connection to Ethernet with NetworkManager |
1,401,895,989,000 |
With a bash script, can I read the mac address of my eth0 and print it to a file?
|
ifconfig will output information about your interfaces, including the MAC address:
$ ifconfig eth0
eth0 Link encap:Ethernet HWaddr 00:11:22:33:44:55
inet addr:10.0.0.1 Bcast:10.0.0.255 Mask:255.0.0.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:289748093 errors:0 dropped:0 overruns:0 frame:0
TX packets:232688719 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:3264330708 (3.0 GiB) TX bytes:4137701627 (3.8 GiB)
Interrupt:17
The HWaddr is what you want, so you can use awk to filter it:
$ ifconfig eth0 | awk '/HWaddr/ {print $NF}'
00:11:22:33:44:55
Redirect that into a file:
$ ifconfig eth0 | awk '/HWaddr/ {print $NF}' > filename
| Print mac address to file |
1,401,895,989,000 |
I have set up a network as such:
Set up host-only networking on VirtualBox. The first adapter is configured with NAT, the second with host-only networking
HOST: Windows
GUEST: CentOS VM1, CentOS VM2 (clone of VM1)
When executing ifconfig -a on both VMs, I noticed that the MAC addresses are exactly the same. My question is how am I able to ping from VM1 to VM2 considering that the MAC addresses are the same?
VM1:
eth0 Link encap:Ethernet HWaddr 08:00:27:AF:A3:28
inet addr:10.0.2.15 Bcast:10.0.2.255 Mask:255.255.255.0
inet6 addr: fe80::a00:27ff:feaf:a328/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:27 errors:0 dropped:0 overruns:0 frame:0
TX packets:47 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:10671 (10.4 KiB) TX bytes:5682 (5.5 KiB)
eth1 Link encap:Ethernet HWaddr 08:00:27:C4:A8:B6
inet addr:192.168.56.102 Bcast:192.168.56.255 Mask:255.255.255.0
inet6 addr: fe80::a00:27ff:fec4:a8b6/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:859 errors:0 dropped:0 overruns:0 frame:0
TX packets:41 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:114853 (112.1 KiB) TX bytes:4823 (4.7 KiB)
ip -6 addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 16436
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qlen 1000
inet6 fe80::a00:27ff:feaf:a328/64 scope link
valid_lft forever preferred_lft forever
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qlen 1000
inet6 fe80::a00:27ff:fec4:a8b6/64 scope link
valid_lft forever preferred_lft forever
VM2:
eth0 Link encap:Ethernet HWaddr 08:00:27:AF:A3:28
inet addr:10.0.2.15 Bcast:10.0.2.255 Mask:255.255.255.0
inet6 addr: fe80::a00:27ff:feaf:a328/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:114 errors:0 dropped:0 overruns:0 frame:0
TX packets:151 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:41594 (40.6 KiB) TX bytes:13479 (13.1 KiB)
eth1 Link encap:Ethernet HWaddr 08:00:27:C4:A8:B6
inet addr:192.168.56.101 Bcast:192.168.56.255 Mask:255.255.255.0
inet6 addr: fe80::a00:27ff:fec4:a8b6/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:1900 errors:0 dropped:0 overruns:0 frame:0
TX packets:78 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:259710 (253.6 KiB) TX bytes:9736 (9.5 KiB)
ip -6 addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 16436
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qlen 1000
inet6 fe80::a00:27ff:feaf:a328/64 scope link
valid_lft forever preferred_lft forever
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qlen 1000
inet6 fe80::a00:27ff:fec4:a8b6/64 scope link tentative dadfailed
valid_lft forever preferred_lft forever
|
This is one of those things that surprises people because it goes against what they've been taught.
2 machines with the same hardware mac address on the same broadcast domain can talk to each other just fine as long as they have different IP addresses (and the switching gear plays nice).
Lets start with a test setup:
VM1 $ ip addr show dev enp0s8
3: enp0s8: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
link/ether 08:00:27:3c:f9:ad brd ff:ff:ff:ff:ff:ff
inet 169.254.0.2/24 scope global enp0s8
valid_lft forever preferred_lft forever
inet6 fe80::a00:27ff:fe3c:f9ad/64 scope link
valid_lft forever preferred_lft forever
VM2 $ ip addr show dev enp0s8
3: enp0s8: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
link/ether 08:00:27:3c:f9:ad brd ff:ff:ff:ff:ff:ff
inet 169.254.0.3/24 scope global enp0s8
valid_lft forever preferred_lft forever
inet6 fe80::a00:27ff:fe3c:f9ad/64 scope link tentative dadfailed
valid_lft forever preferred_lft forever
So notice how both machines have the same MAC addr, but different IPs.
Lets try pinging:
VM1 $ ping -c 3 169.254.0.3
PING 169.254.0.3 (169.254.0.3) 56(84) bytes of data.
64 bytes from 169.254.0.3: icmp_seq=1 ttl=64 time=0.505 ms
64 bytes from 169.254.0.3: icmp_seq=2 ttl=64 time=0.646 ms
64 bytes from 169.254.0.3: icmp_seq=3 ttl=64 time=0.636 ms
--- 169.254.0.3 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2001ms
rtt min/avg/max/mdev = 0.505/0.595/0.646/0.070 ms
So, the remote host responded. Well, that's weird. Lets look at the neighbor table:
VM1 $ ip neigh
169.254.0.3 dev enp0s8 lladdr 08:00:27:3c:f9:ad REACHABLE
10.0.2.2 dev enp0s3 lladdr 52:54:00:12:35:02 STALE
That's our MAC!
Lets do a tcpdump on the other host to see that it's actually getting the traffic:
VM2 $ tcpdump -nn -e -i enp0s8 'host 169.254.0.2'
16:46:21.407188 08:00:27:3c:f9:ad > 08:00:27:3c:f9:ad, ethertype IPv4 (0x0800), length 98: 169.254.0.2 > 169.254.0.3: ICMP echo request, id 2681, seq 1, length 64
16:46:21.407243 08:00:27:3c:f9:ad > 08:00:27:3c:f9:ad, ethertype IPv4 (0x0800), length 98: 169.254.0.3 > 169.254.0.2: ICMP echo reply, id 2681, seq 1, length 64
16:46:22.406469 08:00:27:3c:f9:ad > 08:00:27:3c:f9:ad, ethertype IPv4 (0x0800), length 98: 169.254.0.2 > 169.254.0.3: ICMP echo request, id 2681, seq 2, length 64
16:46:22.406520 08:00:27:3c:f9:ad > 08:00:27:3c:f9:ad, ethertype IPv4 (0x0800), length 98: 169.254.0.3 > 169.254.0.2: ICMP echo reply, id 2681, seq 2, length 64
16:46:23.407467 08:00:27:3c:f9:ad > 08:00:27:3c:f9:ad, ethertype IPv4 (0x0800), length 98: 169.254.0.2 > 169.254.0.3: ICMP echo request, id 2681, seq 3, length 64
16:46:23.407517 08:00:27:3c:f9:ad > 08:00:27:3c:f9:ad, ethertype IPv4 (0x0800), length 98: 169.254.0.3 > 169.254.0.2: ICMP echo reply, id 2681, seq 3, length 64
So, as you can see, even though the traffic has the same source and destination hardware mac address, everything still works perfectly fine.
The reason for this is that the MAC address lookup comes very late in the communication process. The box has already used the destination IP address, and the routing tables to determine which interface it is going to send the traffic out on. The mac address that it adds onto the packet comes after that decision.
I should also note that this is dependent upon the layer 2 infrastructure. How these machines are connected, and what sits between them. If you've got a more intelligent switch, this may not work. It may see this packet coming through and reject it.
Now, going on to the traditional belief, of that this doesn't work. Well it is true, from a certain point of view :-)
The problem arises when another host on the network needs to talk to either of these machines. When the traffic goes out, the switch is going to route the traffic by the destination mac address, and it's only going to send it to a single host.
There are a few possible reasons why this test setup works:
The traffic is broadcast to all ports, or to all ports which the MAC matches.
The switch discards the source port as an option when determining the destination port.
The switch is actually a layer 3 switch and is routing based on the IP address, and not the mac address.
| Identical MAC address on two different VM, yet I have internet connectivity |
1,401,895,989,000 |
I have a problem with an ASUSPRO B8430UA laptop: when I boot it with Ubuntu 16.04 (or NixOS 16.03) the Ethernet port does not work. The driver used is e1000e, it reports:
$ dmesg | grep e1000e
[ 5.643760] e1000e: Intel(R) PRO/1000 Network Driver - 3.2.6-k
[ 5.643761] e1000e: Copyright(c) 1999 - 2015 Intel Corporation.
[ 5.644308] e1000e 0000:00:1f.6: Interrupt Throttling Rate (ints/sec) set to dynamic conservative mode
[ 5.877838] e1000e 0000:00:1f.6: The NVM Checksum Is Not Valid
[ 5.907340] e1000e: probe of 0000:00:1f.6 failed with error -5
Under Windows 7 Ethernet port works fine: I can connect to the Internet.
According to Windows, I have Intel(R) Ethernet Connection I219-V.
I have searched for "official" Linux drivers, but none is listed as supporting I219-V. However, e1000e is listed as supporting I218-V, and I've got a confirmation from e1000-devel mailing list that e1000e should support I219-V. Just in case I tried using the latest version 3.3.4 of e1000e, but the error was the same: "The NVM Checksum Is Not Valid."
It looks like indeed there is a mismatch of the checksum of the non-volatile memory of I219-V.
I have tried another ASUS laptop of the same model, and the error was the same, so this does not look like an accidental corruption.
Neither ASUS nor Intel customer support could suggest any solution.
I have discovered Intel Ethernet Connections Boot Utility, but according to the documentation (for version 1.6.13.0) it is only intended for PCI, not OEM on-board, Ethernet cards. However, I decided to run it without parameters just to print the list of Intel network ports, and this is what I've got:
$ sudo ./bootutil64e
Intel(R) Ethernet Flash Firmware Utility
BootUtil version 1.6.13.0
Copyright (C) 2003-2016 Intel Corporation
Type BootUtil -? for help
Port Network Address Location Series WOL Flash Firmware Version
==== =============== ======== ======= === ============================= =======
1 D017C2201F59 0:31.6 Gigabit N/A FLASH Not Present
I do not quite understand what "FLASH Not Present" means here.
I posed a question on SuperUser.SE about fixing the NVM checksum.
Here I am asking if and how anyone managed to successfully install Linux with working Ethernet on an ASUSPRO B8430UA laptop or on any other laptops with Intel Ethernet Controllers which had "The NVM Checksum Is Not Valid" error.
|
I managed to fix the checksum. Now Ethernet works fine under Linux. I explained the details in my answer to my SuperUser.SE question.
Basically, I first patched e1000e to skip the NVM checksum validation
for (i = 0;; i++) {
if (e1000_validate_nvm_checksum(&adapter->hw) >= 0)
break;
if (i == 2) {
dev_err(pci_dev_to_dev(pdev),
"The NVM Checksum Is Not Valid\n");
err = -EIO;
goto err_eeprom;
}
}
in src/netdev.c, and after I had access to the Ethernet chip, I wrote to its NVM with ethtool, which automatically fixed the checksum.
| Intel Ethernet Connection I219-V not working under Linux on an ASUSPRO B laptop, e1000e driver reports: "The NVM Checksum Is Not Valid" |
1,401,895,989,000 |
I have CentOS 6.3 running in a (virtual) machine with two Ethernet adapters. I have eth0 connected to a TCP/IP LAN and eth1 connected to a DSL modem. The system is intended as a dedicated router/firewall, and has iptables set up to do SNAT, DNAT, and the desired filtering.
This was working great but I changed DSL modems and unfortunately the new (faster) one is idiotproofed and so automatically does NAT and will not allow me to pass my public IP along to eth1. I can't tolerate double NAT so I did some research and read that this modem can be 'tricked' into giving my computer a public IP by doing the PPPoE on the computer.
I therefore set up pppd to use eth1, creating the ppp0 connection which I then substitute for eth1 in my custom iptables config script. This seems to work to a degree but I had to open up the firewall to get it to work, and it's flaky.
Partly to help in troubleshooting, I want to totally rule out the possibility of any TCP/IP traffic being directly routed to eth1 where my 'friendly' modem will happily NAT it.
To the best of my knowledge, PPPoE sits below, not above IP - on the physical interface it deals directly in Ethernet frames. Therefore I should not even have to have IP networking configured on eth1 at all in order for pppd to work, and IP networking running on eth1 therefore is just complicating matters needlessly.
Here's where I discover, silly me, I don't know how to disable the TCP/IP stack on Linux! I know on a Windows box you can just uncheck the TCP/IP protocol in the adapter properties, but here I am running a text-only CentOS and I have no idea how to do it.
Apparently it's not a very common desire, because I've been searching the Internet to no avail. It seems like a hard-wired assumption that an Ethernet adapter is a TCP/IP connection. Well, usually...
Thanks for any help!
Kevin
|
Just remove the IPv4 and IPv6 addresses with ip addr flush dev eth1 and ip -6 addr flush dev eth1.
| How can I disable TCP/IP for an Ethernet adapter? |
1,401,895,989,000 |
My problem is that I need to backup the files on my Linux machine to my Windows laptop. My external hard drive died, and so backing up to an external drive is out of the question for the time being.
These are the methods I've tried:
Samba
Samba with Gadwin GUI
Windows Shared Folder, Wirelessly (I can't access it, even though both machines indicate a connection)
I don't want to try Samba again, because it's just too complex for me -- the 15-odd tutorials I used were either incomplete or assumed too much knowledge on the part of the reader. I've spent about 8 hours trying to make it work and I give up.
I've heard that you can connect two computers with an ethernet cable. Only problem is that it's not a cross-over cable, and I don't have a router, so they would have to be directly connected with a regular rj-45 cable.
I don't want to upload files to the cloud, because I have a lot of files to transfer and want it to be speedy.
|
NitroShare may be able to do what you're looking for. It is a small app that allows files to quickly be sent between machines on the same network.
Once installed on both your Linux and Windows machines, the two machines should automatically discover each other. Use the menu in the system tray to send a file or directory to a specific machine on the network:
Download links are available here.
| Transfer files between Windows and Linux machines? |
1,401,895,989,000 |
I have two Linux boxes. One is running KNOPPIX and the other Ubuntu. I have only one wifi dongle between them, and only one of them has an Ethernet port. They both have free USB ports however. I need the box with the dongle to share the connection through a male-to-male USB cable.
I know it is possible to do a similar setup with a desktop and certain portable devices, but I need it between two normal computers. I cannot buy any additional hardware.
|
Without any deeper knowledge, I would suggest looking at the Linux USB Project, section USB Host-to-Host Cables, and possibly Easy Transfer Cable (although that seems to be mainly a Windows thingy). In any case you are likely to need additional hardware, because the cable probably is not "just wires".
| How do I share an internet connection through USB? |
1,401,895,989,000 |
Currently the Ethernet ports in the building I work in are down, but the Wi-Fi works. I have a Wi-Fi-enabled laptop (Ubuntu 14.04 LTS (Trusty Tahr)) and a non-Wi-Fi enabled workstaion (Debian 8 (Jessie)) with only an Ethernet plug.
Is it possible to connect the two via an Ethernet cable and be able to get network connectivity on the workstation?
|
Yes, you can do this, and it's not even that hard. I have a laptop with a wireless card, and an ethernet port. I plugged a RapberryPi running Arch Linux into it, via a "crossover" ethernet cable. That's one special thing you might need - not all ethernet cards can do a machine-to-machine direct connection.
The other tricky part is IP addressing. It's best to illustrate this. Here's my little set-up script. Again, enp9s0 is the laptop's ethernet port, and wlp12s0 is the laptop's wireless device.
#!/bin/bash
/usr/bin/ip link set dev enp9s0 up
/usr/bin/ip addr add 172.16.1.1/24 dev enp9s0
sleep 10
modprobe iptable_nat
echo 1 > /proc/sys/net/ipv4/ip_forward
iptables -t nat -A POSTROUTING -s 172.16.1.0/24 -j MASQUERADE
iptables -A FORWARD -o enp9s0 -i wlp12s0 -s 172.16.1.0/24 -m conntrack --ctstate NEW -j ACCEPT
iptables -A FORWARD -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
dhcpd -cf /etc/dhcpd.enp9s0.conf enp9s0
The script sets a static IP address for the ethernet card, 172.16.1.1, then sets up NAT by loading a kernel module. It turns on IP routing (on the laptop), then does some iptables semi-magic to get packets routed from the wireless card out the ethernet, and vice versa.
I have dhcpd running on the ethernet port to give out IP addresses because that's what the Raspberry Pi wants, but you could do a static address on your workstation, along with static routing, DNS server, and NTP server.
The file /etc/dhcpd.enp9s0.conf looks like this, just in case you go down that route:
option domain-name "subnet";
option domain-name-servers 10.0.0.3;
option routers 172.16.1.1;
option ntp-servers 10.0.0.3;
default-lease-time 14440;
ddns-update-style none;
deny bootp;
shared-network intranet {
subnet 172.16.1.0 netmask 255.255.255.0 {
option subnet-mask 255.255.255.0;
pool { range 172.16.1.50 172.16.1.200; }
}
}
The IP address choice is pretty critical. I used 172.16.1.0/24 for the ethernet cable coming out of the laptop. The wireless card on the laptop ends up with a 192.161.1.0/24 . You need to look at what IP address the laptop's wireless has, and choose some other subnet for the ethernet card. Further, you need to choose one of the "bogon" or "non-routable" networks. In my example, 172.16.1.0/24 is from the official non-routable ranges of IP addresses, as is 192.168.1.0/24, and so is the 10.0.0.3 address dhcpd.enp9s0.conf gives out for a DNS server and NTP server. You'll have to use your head to figure out what's appropriate for your setup.
| "Pipe" Wi-Fi signal through Ethernet cable |
1,401,895,989,000 |
I'm using elementary OS (based on Ubuntu 12.04) and yesterday I woke up to no wired ethernet connection. As far as I can remember I changed absolutely nothing, it was working at night and not anymore the next morning.
If I plug in my USB wi-fi antennae it picks it up immediately so it's not my connection/modem. If I start my PC with Ubuntu ethernet works fine so it's not something physically broken.
Here are some outputs:
$ifconfig -a
lo Link encap:Bucle local
Direc. inet:127.0.0.1 Másc:255.0.0.0
Dirección inet6: ::1/128 Alcance:Anfitrión
ACTIVO BUCLE FUNCIONANDO MTU:16436 Métrica:1
Paquetes RX:2279 errores:0 perdidos:0 overruns:0 frame:0
Paquetes TX:2279 errores:0 perdidos:0 overruns:0 carrier:0
colisiones:0 long.colaTX:0
Bytes RX:201028 (201.0 KB) TX bytes:201028 (201.0 KB)
wlan0 Link encap:Ethernet direcciónHW 00:25:9c:a4:32:51
Direc. inet:192.168.1.101 Difus.:192.168.1.255 Másc:255.255.255.0
Dirección inet6: fe80::225:9cff:fea4:3251/64 Alcance:Enlace
ACTIVO DIFUSIÓN FUNCIONANDO MULTICAST MTU:1500 Métrica:1
Paquetes RX:53991 errores:0 perdidos:0 overruns:0 frame:0
Paquetes TX:43111 errores:0 perdidos:0 overruns:0 carrier:0
colisiones:0 long.colaTX:1000
Bytes RX:57986158 (57.9 MB) TX bytes:16845669 (16.8 MB)
$sudo ethtool eth0
Settings for eth0:
Cannot get device settings: No such device
Cannot get wake-on-lan settings: No such device
Cannot get message level: No such device
Cannot get link status: No such device
No data available
$sudo dhclient eth0
Cannot find device "eth0"
My /etc/network/interfaces file contains:
auto lo
iface lo inet loopback
So there's definitely something wrong with my eth0 settings but I just don't know how it is or how to fix it. Any help will be much appreciated.
Add
Here's the output from sudo lshw -c network -sanitize:
*-network NO RECLAMADO
descripción: Ethernet controller
producto: RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller
fabricante: Realtek Semiconductor Co., Ltd.
id físico: 0
información del bus: pci@0000:04:00.0
versión: 06
anchura: 64 bits
reloj: 33MHz
capacidades: pm msi pciexpress msix vpd bus_master cap_list
configuración: latency=0
recursos: ioport:d000(size=256) memoria:d0004000-d0004fff memoria:d0000000-d0003fff
*-network
descripción: Interfaz inalámbrica
id físico: 1
información del bus: usb@1:5
nombre lógico: wlan0
serie: [REMOVED]
capacidades: ethernet physical wireless
configuración: broadcast=yes driver=rt2800usb driverversion=3.2.0-60-generic-pae firmware=0.29 ip=[REMOVED] link=yes multicast=yes wireless=IEEE 802.11bg
where "NO RECLAMADO" means "NOT CLAIMED".
|
I would start at the bottom of the stack and confirm that the Ethernet device is actually getting detected by the OS first.
Example
$ sudo lshw -c network -sanitize
*-network
description: Ethernet interface
product: 82577LM Gigabit Network Connection
vendor: Intel Corporation
physical id: 19
bus info: pci@0000:00:19.0
logical name: em1
version: 06
serial: [REMOVED]
capacity: 1Gbit/s
width: 32 bits
clock: 33MHz
capabilities: pm msi bus_master cap_list ethernet physical tp 10bt 10bt-fd 100bt 100bt-fd 1000bt-fd autonegotiation
configuration: autonegotiation=on broadcast=yes driver=e1000e driverversion=2.3.2-k firmware=0.12-1 latency=0 link=no multicast=yes port=twisted pair
resources: irq:43 memory:f2600000-f261ffff memory:f2625000-f2625fff ioport:1820(size=32)
From this type of output you can start to confirm that there is an actual driver attached to your Ethernet device and that's at least getting detected by the kernel during boot.
UPDATE #1
Based on this output from your updates:
$ sudo lshw -c network -sanitize:
*-network NO RECLAMADO
descripción: Ethernet controller
producto: RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller
...
fabricante: Realtek Semiconductor Co., Ltd.
id físico: 0
información del bus: pci@0000:04:00.0
versión: 06
anchura: 64 bits
reloj: 33MHz
capacidades: pm msi pciexpress msix vpd bus_master cap_list
configuración: latency=0
recursos: ioport:d000(size=256) memoria:d0004000-d0004fff memoria:d0000000-d0003fff
You should notice that the "configuration" line doesn't specify a kernel module (driver). This is likely your issue.
I did find this thread which sounds related to your issue (even though it's with Ubuntu). The thread is titled: "Thread: 13.10 RTL8111/8168/8411 slow internet". I'd try loading this module to see if it'll work with your particular hardware:
$ sudo modprobe r8169
You can check the output of dmesg afterwards to see if the module loaded successfully.
If this works you can make it permanent by adding this module to you system's list of modules to load at bootup.
$ echo "r8169" | sudo tee -a /etc/modules >/dev/null
You could also add an association in the /etc/modprobe.d/ directory which would associate the device, r6168 with the r6169.
| No wired ethernet connection |
1,401,895,989,000 |
I'm almost to the point where I can post the solution I wound up with for my complex port bonding question. However, in reading the bonding.txt file, I see this option text:
ad_select
Specifies the 802.3ad aggregation selection logic to use. The possible values and their effects are:
stable or 0
The active aggregator is chosen by largest aggregate bandwidth.
Reselection of the active aggregator occurs only when all slaves of the active aggregator are down or the active aggregator has no slaves.
This is the default value.
bandwidth or 1
The active aggregator is chosen by largest aggregate bandwidth. Reselection occurs if:
- A slave is added to or removed from the bond
- Any slave's link state changes
- Any slave's 802.3ad association state changes
- The bond's administrative state changes to up
count or 2
The active aggregator is chosen by the largest number of ports (slaves). Reselection occurs as described under the "bandwidth" setting, above.
The way this is written, I can't tell if a single bond can contain more than one aggregator, or not! If the bonding module is smart enough to sort out more than one aggregation within a bond, I'm golden!
Let me simplify my drawing from over there:
____________ eth1 ________ eth2 ____________
| switch 1 |========| host |--------| switch 2 |
------------ eth3 -------- ------------
These switches do not do 802.3ad across switches. So, if I put all three interfaces into a single 802.3ad bond, do I get two aggregators? One containing eth1 & eth3, the other just holding eth2? Conceivably, the LACP signals between the host and the switches would be enough to do that. I just don't know if that capability is actually built in.
Anyone? Anyone? Can I get two aggregators out of a single interface bond?
|
Yes, given the following config:
.-----------. .-----------.
| Switch1 | | Switch2 |
'-=-------=-' '-=-------=-'
| | | |
| | | |
.-=----.--=---.---=--.----=-.
| eth0 | eth1 | eth2 | eth3 |
|---------------------------|
| bond0 |
'---------------------------'
Where each switch has its two ports configured in a PortChannel, the Linux end with the LACP bond will negotiate two Aggregator IDs:
Aggregator ID 1
- eth0 and eth1
Aggregator ID 2
- eth2 and eth3
And the switches will have a view completely separate of each other.
Switch 1 will think:
Switch 1
PortChannel 1
- port X
- port Y
Switch 2 will think:
Switch 2
PortChannel 1
- port X
- port Y
From the Linux system with the bond, only one Aggregator will be used at a given time, and will fail over depending on ad_select.
So assuming Aggregator ID 1 is in use, and you pull eth0's cable out, the default behaviour is to stay on Aggregator ID 1.
However, Aggregator ID 1 only has 1 cable, and there's a spare Aggregator ID 2 with 2 cables - twice the bandwidth!
If you use ad_select=count or ad_select=bandwidth, the active Aggregator ID fails over to an Aggregator with the most cables or the most bandwidth.
Note that LACP mandates an Aggregator's ports must all be the same speed and duplex, so I believe you could configure one Aggregator with 1Gbps ports and one Aggregator with 10Gbps ports, and have intelligent selection depending on whether you have 20/10/2/1Gbps available.
If this doesn't make sense, let me know, I'd love to improve this answer. LACP is a fantastic protocol which can do a lot of things people don't know about, this is one of the common ones.
People always want to "bond bonds" which cannot be done, but LACP allows the same setup with even more advantages and smart link selection.
Note on VPC
Some switches can be configured to "logically join" an Aggregator, so then the two switches act as one Aggregator ID. This is commonly called "Virtual Port Channel" or "Multi Chassis Link Aggregation" (MLAG).
This is possible, but is not what we're talking about here. In this answer, we're talking about two discrete switches which have no knowledge of each other.
| Bonds vs. Aggregators |
1,401,895,989,000 |
i am using centos 7. I am typing the command
ip addr show eth0
but its reply Device "eth0" does not exist.
|
In CentOS, network interfaces are named differently. So they aren't called eth0 or eth1, but rather have names like eno1 or enp2s0. (Source.)
Run ip addr to see how these interfaces are named on your system.
These names are defined in /etc/sysconfig/network-scripts/ifcfg-<iface>. You can change their names if you really wanted to, but I don't recommend it.
| Device "eth0" does not exist |
1,384,222,990,000 |
I know that I can find which network interface is currently being used by parsing the output of:
# ifconfig
or
# route
But how can I get this information as a non-root user? Is there a way I can build such a
$ magic-command
whose ouput would be none lo or wlan0 or eth0 depending on the device used.. or even enp3s0f1 or wlp2s0 on exotic systems, with no admin rights?
|
Something like this?
ip addr | awk '/state UP/ {print $2}'
enp0s3:
This command was issued as a "regular" (non-root) user on:
uname -a
Linux centos 3.10.0-514.el7.x86_64 #1 SMP Tue Nov 22 16:42:41 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux
If it is important to remove the trailing : from the interface name, use (for example):
ip addr | awk '/state UP/ {print $2}' | sed 's/.$//'
enp0s3
| How can I find active network interface from userland? |
1,384,222,990,000 |
I want to connect a PC to the internet via my notebook, which is connected to a WLAN.
The setup should look like the following scheme:
PC (eth0) -> Notebook (eth0) -> Notebook(wlan0) -> Router.
Both are running linux - arch on the notebook and funtoo on the PC.
Edit: So I tried rush's method and it didn't work for me, here is what I did:
PC:
ifconfig eth0 192.168.2.3
route add default gateway 192.168.2.2
nameserver 8.8.8.8 > resolv.conf
Notebook:
echo 1 > /proc/sys/net/ipv4/ip_forward
iptables -t nat -A POSTROUTING -o wlan0 -j SNAT --to-source 192.168.2.101
192.168.2.101 is the wlan0 IP address. I can't ping 192.168.2.2 (connect: Network is unreachable) and the connection doesn't seem to be working anymore on the notebook.
|
It's pretty easy. You need to connect PC to notebook. Configure eth0 on PC (set for example ip = 192.168.2.3 and default gateway 192.168.2.2 and dns server to 8.8.8.8). That's all you need to do on PC.
On notebook you need to set up the internet connection as usual and configure eth0 with the following way: set ip address to 192.168.2.2, enable net forwarding with iptables.
Hope you're able to set up ip, gw and dns. To set up forwarding execute following script from root user:
#!/bin/sh
echo 1 > /proc/sys/net/ipv4/ip_forward
INET="wlan0"
INETIP="$(ifconfig $INET | sed -n '/inet addr/{s/.*addr://;s/ .*//;p}')"
iptables -t nat -A POSTROUTING -o $INET -j SNAT --to-source $INETIP
Watch out any specific iptables rules you're already have.
To disable them you can execute before the script above:
iptables -F INPUT
iptables -F FORWARD
iptables -F OUTPUT
iptables -P INPUT ACCEPT
iptables -P OUTPUT ACCEPT
iptables -P FORWARD ACCEPT
And voila, you have the internet on PC.
| Using the Wifi of a notebook via ethernet for another PC |
1,384,222,990,000 |
We have a RHEL 5.5 box with 8 interfaces. And the eth interface naming is flip flopping. Sometimes eth0 comes up on physical port 7th, and sometimes on another physical port.
We want the naming to be as per the sequence of PCI BUS. I did the research and found that
cat /sys/devices/pci0000\:00/0000\:00\:1e.0/0000\:07\:07.0/net\:eth0/address\
This locations have the mac address of the eth devices. So If I get "address" in sequence from this pci bus locations and put them in ifconfig-eth0 to ifconfig-eth7 in order of PCI BUS location, my eth naming will be stable.
I tried:
find /sys/devices/ -name "address"
but it does not bring any results. I don't know why…
Any help here?
|
Have you tried including the MAC addresses in the different ifcfg-ethX files for the various ethernet devices? Additionally you can control which device get's which ethX handle through udev's 60-net.rules file.
For example
# /etc/sysconfig/network-scripts/ifcfg-eth0
# Intel Corporation 82573E Gigabit Ethernet Controller (Copper)
DEVICE=eth0
BOOTPROTO=static
DHCPCLASS=
HWADDR=00:30:48:56:A6:2E
IPADDR=10.10.10.15
NETMASK=255.255.255.192
ONBOOT=yes
Then in the file /etc/udev/rules.d/60-net.rules:
KERNEL=="eth*", SYSFS{address}=="00:30:48:56:A6:2E", NAME="eth0"
I believe this information is used to keep the devices configured consistently from boot to boot.
Configuring more than one ethX device
To deal with more devices simply setup each devices corresponding /etc/sysconfig/network-scripts/ifcfg-ethX file, and add another line to the 60-net.rules file.
KERNEL=="eth*", SYSFS{address}=="00:30:48:56:A6:2E", NAME="eth0"
KERNEL=="eth*", SYSFS{address}=="00:30:48:56:A6:2F", NAME="eth1"
The above is how you do it in CentOS 5.X. The file changes in CentOS 6.x to 70-persistent-net.rules, and the format is slightly different too:
SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="54:52:00:ff:ff:dd", ATTR{type}=="1", KERNEL=="eth*", NAME="eth0"
References
keeping eth0 as ETH0. - pwrusr.com blog
| RHEL: Creating stable names for network interfaces |
1,384,222,990,000 |
I am looking to do this on a Raspberry Pi, but I don't mind which operating system I have to install, so the easiest most out-of-the-box solution for Pidora (Fedora 20 Remix), Raspbian (Debian) or Arch is the one I'd like.
I am living in a university building where internet access is supplied via a protected wireless network. This wireless network is authorised using WPA2-Enterprise PEAP and requires me to supply a username, password, and authentication certificate. The university provides a script to automatically configure a Linux machine for this network, and the script is happy working with either wpa_supplicant or network-manager - I've tried both.
I have a lot of machines (a mixture of Linux and Windows) which all talk to one another via my own private wireless router. This router has a WAN port meant to face an internet connection, so as to share that connection with all machines on its wireless network.
My aim is to have my Raspberry Pi connect to the university's protected wireless network and then provide an internet connection to the WAN port on my private wireless router. I've decided to use a Raspberry Pi because it's the lowest overhead device I have access to that is able to connect to my university's protected wireless network.
I do not need to be able to see my Raspberry Pi on my private wireless network (if I could that would be fine, but I'm really after the simplest configuration possible). All I need is for my Raspberry Pi to handle authentication to the university wireless network, and then transparently pass data between eth0 and wlan0. To any device plugged into my Raspberry Pi using an ethernet cable, the Raspberry Pi should just look like straight-forward internet gateway.
To summarise, I'm looking for,
(University Wi-Fi with WPA2 PEAP) -> (RPi wlan0)---(RPi eth0) -> (WAN on Private Router)
I've tried using bridge-utils on Debian, but this always seems to knock out my Raspberry Pi's wireless connection.
I've also read about using iptables and ebtables but, as yet, I don't really understand what I'm meant to be doing there, and some of the configurations I've found on the internet seem to conflict with one another.
I should add that the university wireless network dynamically assigns my Raspberry Pi an IP address on wlan0 each time it connects. My private router handles dynamic IP address assignment for all of my machines.
I would be so grateful if anyone could outline some simple clear instructions for achieving the setup I'm after. I am of course willing to read up on and learn anything I need to get this running, but I am interested in keeping the solution as simple and easy to reproduce as possible. The only device I want to configure is the Raspberry Pi.
I note that what I'm trying to do should be possible, because it's perfectly simple to share my university wireless network via my ethernet port on my Windows laptop!
Many thanks in advance!
|
This is as simple as it could be. You do not need any bridging.
Just MASQUERADE your local network on RPi:
iptables -t nat -A POSTROUTING -o wlan0 -j MASQUERADE
Enable forwarding of traffic:
echo 1 > /proc/sys/net/ipv4/ip_forward
RPi will not work as invisible bump-on-the-wire but will need a network setup between
it and your private router – which will use ip address of RPi's eth0 as gateway.
So it will look like this:
(RPi wlan0) -- MASQUERADE -- (RPi eth0;192.168.99.254/24) → (WAN on Private Router,192.168.99.1/24)
Cheers,
| How can I most simply transparently bridge traffic between wlan0 and eth0? |
1,384,222,990,000 |
I did an upgrade from Xubuntu 12.04 to 12.10, and I can't connect to the internet now.
When I press the network button on the panel, I see "No network devices available" on top (greyed out), then "VPN Connections", "Enable Networking" with a checkmark next to it, "Information" (greyed out) and "Edit".
Here's the output from some commands that seem relevant:
~ % lspci | grep -i ethernet
03:00.0 Ethernet controller: Realtek Semiconductor Co., Ltd. RTL8111/8168B PCI Express Gigabit Ethernet controller (rev 07)
~ % lspci | grep -i network
02:00.0 Network controller: Intel Corporation Centrino Wireless-N 1030 (rev 34)
~ % sudo lshw -C network
PCI (sysfs)
*-network UNCLAIMED
description: Network controller
product: Centrino Wireless-N 1030
vendor: Intel Corporation
physical id: 0
bus info: pci@0000:02:00.0
version: 34
width: 64 bits
clock: 33MHz
capabilities: pm msi pciexpress bus_master cap_list
configuration: latency=0
resources: memory:f7c00000-f7c01fff
*-network UNCLAIMED
description: Ethernet controller
product: RTL8111/8168B PCI Express Gigabit Ethernet controller
vendor: Realtek Semiconductor Co., Ltd.
physical id: 0
bus info: pci@0000:03:00.0
version: 07
width: 64 bits
clock: 33MHz
capabilities: pm msi pciexpress msix vpd bus_master cap_list
configuration: latency=0
resources: ioport:e000(size=256) memory:f0004000-f0004fff memory:f0000000-f0003fff
~ % uname -a
Linux bleen 3.5.0-030500-generic #201207211835 SMP Sat Jul 21 22:35:55 UTC 2012 x86_64 x86_64 x86_64 GNU/Linux
~ % ifconfig
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:16436 Metric:1
RX packets:472 errors:0 dropped:0 overruns:0 frame:0
TX packets:472 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:35080 (35.0 KB) TX bytes:35080 (35.0 KB)
~ % ifconfig eth0 up
eth0: ERROR while getting interface flags: No such device
I think that UNCLAIMED means I don't have a driver for the Ethernet controller. It seems that the driver should be called something including 816 (I don't remember where I found that), and it does seem to be missing:
~ % lsmod | grep 816
~ %
I tried downloading and installing the driver (after moving on a USB stick from a computer with a connection), but I get this issue:
~/r8168-8.037.00 % sudo ./autorun.sh
Check old driver and unload it.
Build the module and install
make: * /lib/modules/3.5.0-030500-generic/build: No such file or directory. Stop.
make1: [clean] Error 2
make: ** [clean] Error 2
Not sure what to do next.
|
This question turned out to have two answers, both suggested by @JosephR in the comments.
1) Fixing the /lib/modules/3.5.0-030500-generic/build: No such file or directory error while trying to install the ethernet driver just needed a sudo ln -sv /usr/src/linux-headers-$(uname -r) /lib/modules/$(uname -r)/build - after I did that, the driver install from source worked fine, and I got an ethernet connection.
(Presumably repeating the process with the driver for the wireless controller would have made that work too, but I didn't actually try, due to solution #2.)
2) It turned out that if I just booted with the other kernel that was already installed (3.5.0-41-generic instead of 3.5.0-030500-generic - I don't actually know what the difference is), both the ethernet and the wireless worked fine!
It also solved some other problems I was having after the upgrade. So I changed the default boot kernel to that, and will probably stick with that unless I run into other issues.
| No ethernet/wireless connection after dist upgrade - "network UNCLAIMED" |
1,384,222,990,000 |
I've installed docker on Ubuntu 16. Now I can no more connect to my wired network : ubuntu is using docker0 ethernet interface to connect to the network (the wifi interface still works)
To resolve the problem I have to shutdown docker daemon and then shutdown docker0 interface :
$ sudo link set docker0 down
But if I start docker daemon again, it sets docker0 interface up and I loose my local network connexion.
What's wrong with docker0 interface ? How can I resolve this problem ?
Thanks :)
|
Looks like the docker network is interfaring with your host network. You need to customise the docker network , and set it to a different network than your host network before starting docker.
https://docs.docker.com/v17.09/engine/userguide/networking/default_network/custom-docker0/
| docker0 network interface is screwing up my network |
1,384,222,990,000 |
The issue:
I recently bought some new hardware and am running into issues getting Ethernet to work, as no combination of kernels and drivers I've tried is working. I've hypothesized the issue is either faulty hardware, or poor device support (due to how recently its been released). But given what I've tried below, I'm wondering what would be good next steps to resolve the issue.
Platform:
CPU: Intel Core i3-10100
MB: Gigabyte B460M-D3H
Trial and Error:
I've tried (unsuccessfully) with the following combination of kernels and driver versions:
Debian 10.7 (Buster), Kernel 4.19, kernel e1000e
Debian 10.7 (Buster), Kernel 4.19, compiled e1000e 3.8.4
Debian 10.7 (Buster), Kernel 4.19, compiled e1000e 3.8.7
Arch Linux LiveUSB, Kernel 5.9, kernel e1000e
Using the 2020-12-01 Arch Linux installation medium, I get the following diagnostic output from lspci, dmesg, etc.:
ip link
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
uname -a
Linux archiso 5.9.11-arch2-1 #1 SMP PREEMPT Sat, 28 Nov 2020 02:07:22 +0000 x86_64 GNU/Linux
lspci -nn
00:00.0 Host bridge [0600]: Intel Corporation Device [8086:9b63] (rev 03)
00:01.0 PCI bridge [0604]: Intel Corporation Xeon E3-1200 v5/E3-1500 v5/6th Gen Core Processor PCIe Controller (x16) [8086:1901] (rev 03)
00:02.0 VGA compatible controller [0300]: Intel Corporation Device [8086:9bc8] (rev 03)
00:14.0 USB controller [0c03]: Intel Corporation Device [8086:a3af]
00:14.2 Signal processing controller [1180]: Intel Corporation Device [8086:a3b1]
00:16.0 Communication controller [0780]: Intel Corporation Device [8086:a3ba]
00:17.0 SATA controller [0106]: Intel Corporation Device [8086:a382]
00:1b.0 PCI bridge [0604]: Intel Corporation Device [8086:a3e9] (rev f0)
00:1b.4 PCI bridge [0604]: Intel Corporation Device [8086:a3eb] (rev f0)
00:1c.0 PCI bridge [0604]: Intel Corporation Device [8086:a394] (rev f0)
00:1d.0 PCI bridge [0604]: Intel Corporation Device [8086:a398] (rev f0)
00:1f.0 ISA bridge [0601]: Intel Corporation Device [8086:a3c8]
00:1f.2 Memory controller [0580]: Intel Corporation Device [8086:a3a1]
00:1f.3 Audio device [0403]: Intel Corporation Device [8086:a3f0]
00:1f.4 SMBus [0c05]: Intel Corporation Device [8086:a3a3]
00:1f.6 Ethernet controller [0200]: Intel Corporation Ethernet Connection (12) I219-V [8086:0d55]
01:00.0 Serial Attached SCSI controller [0107]: Broadcom / LSI SAS2008 PCI-Express Fusion-MPT SAS-2 [Falcon] [1000:0072] (rev 03)
02:00.0 PCI bridge [0604]: Integrated Technology Express, Inc. IT8892E PCIe to PCI Bridge [1283:8892] (rev 41)
Kernel 4.19 doesn't seem to support my ethernet chipset (device code 0d55), which seems to only be supported in 5.5 and later. So it makes sense not to be supported in my stock Debian Buster install, but it doesn't make sense that the self-compiled 3.8.4/3.8.7 e1000e drivers are still broken, as my chipset should have been supported since version 3.5.1
dmesg | grep e1000e
[ 7.373433] e1000e: Intel(R) PRO/1000 Network Driver
[ 7.373434] e1000e: Copyright(c) 1999 - 2015 Intel Corporation.
[ 7.373684] e1000e 0000:00:1f.6: Interrupt Throttling Rate (ints/sec) set to dynamic conservative mode
[ 7.749973] e1000e 0000:00:1f.6 0000:00:1f.6 (uninitialized): Failed to disable ULP
[ 8.340480] e1000e: probe of 0000:00:1f.6 failed with error -2
Notice the PCI address 0000:00:1f.6, which corresponds to the integrated I219-V chipset from the lspci output.
The ULP error appears in the Arch Linux liveUSB, but it doesn't appear in my Debian Stable tests. However, the probe error still does. An error of -2 corresponds to -E1000_ERR_PHY, which some people report has the following solutions:
Disable wake-from-LAN
Unplug from power and wait anywhere from a few hours to a day and try again
Do not plug in Ethernet until after interface comes online
I've tried these to no avail. It's been suggested by friends on IRC that the ULP (ultra low power) error might indicate the card is constantly stuck in ULP mode, which is why attempting to probe the device fails with a PHY error.
One suggested that this mailing list thread might be relevant, but I'm not sure if attempting to grab their commit source code and applying all the relevant patches myself would be helpful. If someone insists it would, I am happy to try.
UPDATE 1: A friend had the smart idea of trying a fresh Windows install to help diagnose whether it's a hardware issue. After installing Windows 10 and using the provided motherboard driver bundle, the card is recognized but the Windows Device Manager gives a "Device cannot start (Code 10)" error. (I think at this point it's clear it's not a *nix-specific issue, so I should close the question and contact Gigabyte/Intel directly, or ask someone to move this post to the Superuser site.)
|
Turns out, it was most likely a hardware issue. I got a replacement motherboard, and the networking hardware was, curiously enough, recognized by the Debian 10.7 installer (it seems my understanding of which versions of e1000e were included with Debian's kernels was wrong... I should look into that.)
Hopefully other people can use my trial-and-error to avoid the same headache I've had for the past week :)
| e1000e error with B460 Motherboard and Intel I219-V Chipset |
1,384,222,990,000 |
I have enabled the arp support on my dell based server running linux on it. I wanted to
check that if arptables are enabled or not.
Could anyone tell me how do I check the same?
Is it enough to run arp command here?
|
The TCP/IP protocol will not work without ARP so that is always available. Normally ARP works automatically and doesn't require manual intervention.
As the other posts mention cat /proc/net/arp displays the current arp table/cache without using specific tools. You can manipulate the arp cache and static entries with the arp and ip neighbour commands as well.
arptables is a method in the Linux kernel to manage packet filtering on arp packets comparable to the iptables command that manages packet filtering on TCP and UDP packets.
As far as I know the useage of arp filtering is not the default found in most Linux distributions, although most do include the kernel support for arptables. You can typically check for kernel support with modinfo arp_tables.
If the arptables command is also installed arptables -L -n will display any/all rules that are configured.
| How to check if ARP is enabled or not |
1,384,222,990,000 |
In Arch Linux, how can I check if a network device (say eth0) has a carrier signal present?
|
cat /sys/class/net/eth0/carrier is by far the easiest method.
| How can I test the current carrier state for an ethernet adapter in Linux? |
1,384,222,990,000 |
I am looking for a kernel parameter that I could use in the GRUB config to disable EEE (Energy Efficient Ethernet, wikipedia) permanently on my LAN (wired Ethernet) card of my newish laptop:
Basic info:
OS: Linux Mint 21.1 "Vera" Cinnamon
# ethtool -i enp59s0
driver: r8169
version: 5.15.0-56-generic
firmware-version: rtl8168h-2_0.0.2 02/26/15
expansion-rom-version:
bus-info: 0000:3b:00.0
supports-statistics: yes
supports-test: no
supports-eeprom-access: no
supports-register-dump: yes
supports-priv-flags: no
What works (not persistent upon reboots, and sleeps & wakeups):
# ethtool --set-eee enp59s0 eee off
However, I would rather not have to set up a @reboot CRON for this.
What I've tried on a running machine, as suggested here, and here, and other places:
# sysctl -w igb.EEE=0
# sysctl -w e1000e.EEE=0
# sysctl -w r8169.EEE=0
all of which ended up with an error message:
sysctl: cannot stat /proc/sys/[PARAM]/EEE: No such file or directory
Your help is much appreciated.
|
No such kernel parameter exists.
However, there are other ways to achieve your goal than an @reboot cron job.
If you're using NetworkManager, you could create a pre-up dispatcher script (e.g. /etc/NetworkManager/dispatcher.d/pre-up.d/disable-eee) to make the configuration change as the network interface is activated:
#!/bin/sh
#
# Disable EEE on enp59s0
if [ "$1" = "enp59s0" ]; then
/sbin/ethtool --set-eee $1 eee off \
|| /bin/logger "Error $? trying to disable EEE on $1"
fi
exit 0
Be sure to mark the script executable.
Alternatively, you could create /etc/modprobe.d/disable-eee to change the setting as the kernel module is loaded:
install r8169 /sbin/modprobe -i r8169 && sleep 1 && /sbin/ethtool --set-eee enp59s0 eee off
(If the r8169 kernel module is loaded in initramfs boot phase, you might have to run sudo update-initramfs -u before this can take effect on next boot.)
Or you could create your own systemd service unit to run the ethtool command (e.g. /etc/systemd/system/disable-eee.service):
[Unit]
Before=network-pre.target
Wants=network-pre.target
[Service]
Type=oneshot
RemainAfterExit=true
ExecStart=/sbin/ethtool --set-eee enp59s0 eee off
[Install]
WantedBy=multi-user.target
Important Note:
Depending on your OS config, ethtool may be placed someplace else like /usr/sbin/ethtool in Vlastimil's case. If you are unsure, you may run which ethtool or command -v ethtool. The same goes for the logger program.
| How to permanently disable EEE (Energy Efficient Ethernet) on Ethernet card? |
1,384,222,990,000 |
I'm in a situation where I have a 10/100/1000-capable PHY cabled only to support 10/100.
The default behaviour is to use the autonegociation to find the best mode.
At the other end, using a gigabit capable router ends in a non-working interface. I guess autonegociation never converges.
I've heard some people tried with a 100Mbps switch and it works fine.
I'm able to get it working using ethtool but this is quite frustrating :
ethtool -s eth1 duplex full speed 100 autoneg off
What I'd like to do is to keep the autonegociation but withdraw 1000baseT/Full from the choices so that it ends up running seemlessly in 100Mbps. Any way to achieve that using ethtool or kernel options ? (didn't find a thing on my 2.6.32 kernel ...)
(Let's just say some strange dude comes to me with a 10Mbps switch, I need this eth to work with this switch from another century)
|
The thing with autonegotiation is that if you turn it off from one end, the other side can detect the speed but not the duplex mode, which defaults to half. Then you get a duplex mismatch, which is almost the same as the link not working. So if you disable autonegotiation on one end, you practically have to disable it on the other end too.
(Then there's the thing that autonegotiation doesn't actually test the cable, just what the endpoints can do. This can result in a gigabit link over a cable that only has two pairs, and cannot support 1000Base-T.)
But ethtool seems capable of telling the driver what speed/duplex modes to advertise. ethtool -s eth1 advertise 0x0f would allow all 10/100 modes but not 1G.
advertise N
Sets the speed and duplex advertised by autonegotiation. The
argument is a hexadecimal value using one or a combination of
the following values:
0x001 10baseT Half
0x002 10baseT Full
0x004 100baseT Half
0x008 100baseT Full
0x010 1000baseT Half (not supported by IEEE standards)
0x020 1000baseT Full
| Remove SOME advertised link modes with ethtool |
1,384,222,990,000 |
Is there any (reliable) way to find out if the PC booted because of a Wake-on-LAN Packet instead of pressing the power button? I want automatically check if WOL is correctly configured.
I know about ethtool's WOL output, but this just tells me if WOL is turned on, not how the PC booted, right?
|
Manually testing using etherwake
I think you can test it using a tool like etherwake. Depending on the distro it's called etherwake on Ubuntu/Debian, ether-wake on RHEL/CentOS/Fedora. I had it installed already by default on Fedora, it's part of the net-tools package.
To use it:
# Redhat
$ ether-wake 00:11:22:33:44:55
# Debian/Ubuntu
$ etherwake 00:11:22:33:44:55
To confirm that a server support WOL:
$ ethtool eth0
Settings for eth0:
Supported ports: [ ]
Supported link modes:
Supports auto-negotiation: No
Advertised link modes: Not reported
Advertised auto-negotiation: No
Speed: 100Mb/s
Duplex: Full
Port: MII
PHYAD: 1
Transceiver: internal
Auto-negotiation: off
Supports Wake-on: g
Wake-on: g
Link detected: yes
The "Supports Wake-on: g" and "Wake-on: g" tell you that the card is configured for WOL support. If it's missing you can add it to the ifcfg-eth0 config. file like so:
ETHTOOL_OPTS="wol g"
Using hwinfo
I noticed that if you look through the hwinfo there are messages regarding how the system came out of power save mode. Also there are messages related to the ethernet device coming up. For example:
<6>[721194.499752] e1000e 0000:00:19.0: wake-up capability disabled by ACPI
<7>[721194.499757] e1000e 0000:00:19.0: PME# disabled
<7>[721194.499831] e1000e 0000:00:19.0: irq 46 for MSI/MSI-X
<6>[721194.574306] ehci_hcd 0000:00:1a.0: power state changed by ACPI to D0
<6>[721194.576330] ehci_hcd 0000:00:1a.0: power state changed by ACPI to D0
Here are some other messages a little while later:
<6>[721197.226679] PM: resume of devices complete after 3162.340 msecs
<7>[721197.226861] PM: Finishing wakeup.
<4>[721197.226862] Restarting tasks ... done.
<6>[721197.228541] video LNXVIDEO:00: Restoring backlight state
The idea would be that maybe there are some messages here related to how the system came up (WOL or power switch). You could add a script that runs as part of a udev event that could grep through the hwinfo output to see if messages are present for WOL vs. powerswitch. Just a idea at this point.
References
HowTo: Wake Up Computers Using Linux Command [ Wake-on-LAN ( WOL ) ]
ether-wak man page
| Find out if computer started via Wake-on-LAN or power button? |
1,384,222,990,000 |
It is well-known that systemd changes the network interface names from e.g. eth0 to enp0s25, and this is called "Predictable Network Interface Names".
On my system, eth0 is called "enp0s31f6".
And I'm sorry to say this, but I too agree with this user that says "I see little irony in word "predictable"" https://askubuntu.com/questions/704361/why-is-my-network-interface-named-enp0s25-instead-of-eth0
Back on topic:
On my system (Debian 9.8 with one physical PCI Ethernet adapter), I suddenly discovered that DHCP doesn't work any longer.
I need to manually run dhclient to get an IP.
Then, I look into /etc/network/interfaces and see:
auto eth0
iface eth0 inet dhcp
Shouldn't this be enp0s31f6?
However, how am I supposed to know what to put there, what if it changes again, e.g. if I move the Ethernet PCI card to a different slot?
Am I really supposed to edit this file manually, and change eth0 to whatever systemd decides to call my interface?
Surely I must be missing some crucial piece of information here regarding how either systemd works, how Debian works, or how Predictable Network Interfaces work. Perhaps a combination of those.
Am I supposed to refer to an abstract network interface in /etc/network/interfaces? Some abstract string that always means "the first network interface card" (isn't this just eth0?)? Or by some UID? By its PCI domain:bus:device?
This is very confusing, and a lot of documentation refers to what I would consider a mess of legacy scripts, modern systemd, and many distros seem to use a combination of old style scripts and systemd functionality which is hard to grasp.
Questions:
Why did it stop working?
What did I do wrong?
Why was it ever eth0 in my /etc/network/interfaces, when Debian uses systemd and Predictable Network Interfaces?
What is the correct way to fix this?
|
Why did it stop working? What did I do wrong?
It's hard to tell what happened "suddenly". Review your /var/log/syslog or /var/log/messages for DHCP logs around the time it stopped working and you may find out. Also check the modification time in stat /etc/network/interfaces.
Why was it ever eth0 in my /etc/network/interfaces, when Debian uses systemd and Predictable Network Interfaces?
This is the new default since Debian stretch. If you installed your system earlier and your /etc/network/interfaces originates from jessie (or wheezy...) then it was created by the installer (netcfg) using the old naming scheme.
What is the correct way to fix this?
Whatever suits you best.
If you expect to ever have multiple Ethernet interfaces in this machine, then think about how you'd like to tell them apart. Remember that their ethX order would not be stable/predictable. PredictableNetworkInterfaceNames gives you several options, choose according to your use case.
If this machine will only ever have a single Ethernet interface, then you can either
fall back to using the kernel name, which will always be eth0 (the above page gives you several options, my favorite is ln -s /dev/null /etc/systemd/network/99-default.link, just don't forget to regenerate your initramfs afterwards with update-initramfs -u);
or don't care about the name of your interface, ditch /etc/network/interfaces entirely and switch to systemd-networkd with a match-all config like
[Network]
DHCP=ipv4
in /etc/systemd/network/dhcp.network (choose an arbitrary file name).
Sorry, I can't get the indentation right...
| How is systemd supposed to work regarding network interfaces? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.