SlideShare ist ein Scribd-Unternehmen logo
1 von 30
Downloaden Sie, um offline zu lesen
The adventures of poker,
  packets, pipes and
        Python
        Roger Barnes
I like playing online poker
But I could be better at it
I needed a poker buddy

                             All in!




              That's a
            terrible hand!
Live Hold'em Poker Pro
Packet capture options
from your (rooted) Android device - wifi or 3G
● apps - eg Shark for Root
● tcpdump - via shell
Packet capture options
from your router or another device on the
network (if promiscuous mode) - wifi only
● tcpdump/libpcap
● wireshark/tshark
● pcapy
● ngrep
Hackable routers
There are many devices and firmwares to
choose from (see dd-wrt and tomato-usb)

I have Netgear WNR3500L with Tomato-USB
● ssh built in
● Additional packages installed using Optware
  ○ http://tomatousb.org/doc:optware
  ○ Includes python, tshark, ngrep, wget, some build
    tools, ...
Initial capture using tshark

tshark -i eth1 -w capture.pcap -f
"host 192.168.1.106 and
(port 9400 or port 9500)"
Analyse using wireshark - bingo!
IPython Notebook
  http://ipython.org/ipython-doc/dev/interactive/htmlnotebook.html
Parsing game state
More IPython notebook work to figure out
sequence of events, card values, player actions
etc
Mapping card values
def cardmapper(val):
   vals = '23456789TJQKA'
   suits = 'cdhs'
   result = divmod(val, 13)
   return vals[result[1]] + suits[result[0]]
print cardmapper(44) # 7s
print cardmapper(21) # Td
print cardmapper(17) # 6d
print cardmapper(51) # As
print cardmapper(7) # 9c
print cardmapper(0) # 2c
Getting live capture data
● tshark?              Too hard
● pcapy?               Maybe
● ngrep?               Probably
Getting live capture data into Python
● Install pcapy on router?   Too hard
● zmq on router?             Too hard
● SSH and pipe?              Maybe
Running hand analysis
● Run directly on router?   Too hard
Solution - ssh, ngrep and pipes




ssh $router "ngrep ..." | python -u poker-buddy.py
Pipes
Piping data into Python is easy
You can read stdin...
import sys
while True:
    l = sys.stdin.readline():



Alternatively use the Unix-like fileinput
module...
import fileinput
for line in fileinput.input():



... fileinput reads from a list of files, or else stdin
Pipes
Watch out for buffering!

python -u
Now for some poker smarts
Loads of resources on the web
● Poker games generally
  ○ starting hand rankings
  ○ odds calculations etc
Now for some poker smarts
Easy lookup tables in python...
# Unprocessed space separated string dump
stats_rankings = 
"""AA     2.3200     550,632
KK     1.6700     551,878
... lots more lines
32s     -0.1600     369,182"""
# Now convert to structured data
stats_rankings = dict([
   (line.split()[0], (rank + 1, float(line.split()[1])))
   for rank, line
   in enumerate(stats_rankings.split("n"))
])
Now for some poker smarts
Python specific
● pypoker-eval
  ○ Wrapper for poker-eval toolkit
  ○ Run hand simulations
● machine learning systems
  ○ endless possibilities
● Lots of other resources at:
  http://pokerai.org/pf3/viewforum.php?f=32
Code
def read_raw_from_stdin():
    line = ''
    while 1:
        l = sys.stdin.readline()
        line += l.strip()
        if '''we have a complete line''':
             parse_update(line)
             line = ''

if __name__ == "__main__":
    read_raw_from_stdin()
Code
def parse_update(update_str):
    player_cards = get_cards(update_str)
    if player_cards:
        my_cards = [v for v in player_cards if v[0] != '__']
        if my_cards:
            rank_starting_hand(my_cards[0])
    else:
        player_cards = old_player_cards # global state excluded
        community_cards = get_cards(update_str, player=False)
        if community_cards:
            print("Community cards %s" % community_cards)
            rank_hand(player_cards, community_cards)
Code
e = PokerEval()
def rank_hand(pocket_cards, community_cards, iterations=100000):
  unknown_cards = ['__'] * (5 - len(community_cards))
  result = e.poker_eval(game = "holdem",
    pockets = pocket_cards,
    iterations = iterations,
    board = community_cards + unknown_cards)

    for i, data in enumerate(result['eval']):
        print(pocket_cards[i], "%2d%%" % (float(data['ev']) /
10), data['winhi'], data['losehi'], data['tiehi'])
Game in progress - poker-buddy.py
Player cards [['__', '__'], ['__', '__'], ['Ac', 'Kc'],
['__', '__'], ['__', '__']]
Group 1
(5, 0.77)
Game in progress - poker-buddy.py
Community cards ['Th', '5s', '9h']
['__', '__'] 21% 20486 77811 1703
['__', '__'] 21% 20267 78013 1720
['Ac', 'Kc'] 15% 14880 84332 788
['__', '__'] 21% 20386 77819 1795
['__', '__'] 21% 20207 78074 1719
Game in progress - poker-buddy.py
Community cards ['Th', '5s', '9h', 'Jc', '6s']
['__', '__'] 24% 24185 74694 1121
['__', '__'] 24% 24332 74502 1166
['Ac', 'Kc'] 1% 1019 98870 111
['__', '__'] 24% 24005 74893 1102
['__', '__'] 24% 24148 74698 1154
Summary
● Python can be used for packet capture
   ○ pycapy
● Python for data processing
   ○ Pipes, unbuffered input (-u option), stdin, fileinput
     module
● Python on embedded devices
   ○ Optware on routers & other embedded devices
● IPython Notebook great for analysis...
     ...and documenting what you found
● There's a library for almost everything
   ○ eg pypoker-eval
Thanks! Questions?




Code (warts and all):
https://github.com/mindsocket/poker-buddy

Weitere ähnliche Inhalte

Was ist angesagt?

Introduction to IPFS & Filecoin - longer version
Introduction to IPFS & Filecoin - longer versionIntroduction to IPFS & Filecoin - longer version
Introduction to IPFS & Filecoin - longer versionTinaBregovi
 
Pattern based problem solving-published
Pattern based problem solving-publishedPattern based problem solving-published
Pattern based problem solving-publishedteddysoft
 
Qt for beginners part 1 overview and key concepts
Qt for beginners part 1   overview and key conceptsQt for beginners part 1   overview and key concepts
Qt for beginners part 1 overview and key conceptsICS
 
[JCConf 2023] 從 Kotlin Multiplatform 到 Compose Multiplatform:在多平台間輕鬆共用業務邏輯與 U...
[JCConf 2023] 從 Kotlin Multiplatform 到 Compose Multiplatform:在多平台間輕鬆共用業務邏輯與 U...[JCConf 2023] 從 Kotlin Multiplatform 到 Compose Multiplatform:在多平台間輕鬆共用業務邏輯與 U...
[JCConf 2023] 從 Kotlin Multiplatform 到 Compose Multiplatform:在多平台間輕鬆共用業務邏輯與 U...Shengyou Fan
 
Python Modules, Packages and Libraries
Python Modules, Packages and LibrariesPython Modules, Packages and Libraries
Python Modules, Packages and LibrariesVenugopalavarma Raja
 
What is Kotlin Multiplaform? Why & How?
What is Kotlin Multiplaform? Why & How? What is Kotlin Multiplaform? Why & How?
What is Kotlin Multiplaform? Why & How? Shady Selim
 
Windows 10 Nt Heap Exploitation (Chinese version)
Windows 10 Nt Heap Exploitation (Chinese version)Windows 10 Nt Heap Exploitation (Chinese version)
Windows 10 Nt Heap Exploitation (Chinese version)Angel Boy
 
Hack & Fix, Hands on ColdFusion Security Training
Hack & Fix, Hands on ColdFusion Security TrainingHack & Fix, Hands on ColdFusion Security Training
Hack & Fix, Hands on ColdFusion Security TrainingColdFusionConference
 
BAS004-1_伺服器硬體基礎_v181026
BAS004-1_伺服器硬體基礎_v181026BAS004-1_伺服器硬體基礎_v181026
BAS004-1_伺服器硬體基礎_v181026rwp99346
 
Javaで簡単にgpgpu aparapi
Javaで簡単にgpgpu aparapiJavaで簡単にgpgpu aparapi
Javaで簡単にgpgpu aparapiKen'ichi Sakiyama
 
An Introduction to OpenSAF 5.17.2011
An Introduction to OpenSAF 5.17.2011An Introduction to OpenSAF 5.17.2011
An Introduction to OpenSAF 5.17.2011OpenSAF Foundation
 
使用 Passkeys 打造無密碼驗證服務
使用 Passkeys 打造無密碼驗證服務使用 Passkeys 打造無密碼驗證服務
使用 Passkeys 打造無密碼驗證服務升煌 黃
 
.NET 7 升級教戰手冊_V1.0.pdf
.NET 7 升級教戰手冊_V1.0.pdf.NET 7 升級教戰手冊_V1.0.pdf
.NET 7 升級教戰手冊_V1.0.pdfGelis Wu
 
Pharo Networking by Example
Pharo Networking by ExamplePharo Networking by Example
Pharo Networking by ExampleNoury Bouraqadi
 
(2013 DEVIEW) 멀티쓰레드 프로그래밍이 왜이리 힘드나요?
(2013 DEVIEW) 멀티쓰레드 프로그래밍이  왜이리 힘드나요? (2013 DEVIEW) 멀티쓰레드 프로그래밍이  왜이리 힘드나요?
(2013 DEVIEW) 멀티쓰레드 프로그래밍이 왜이리 힘드나요? 내훈 정
 
Construct 2 Platformer: Step by Step
Construct 2 Platformer: Step by StepConstruct 2 Platformer: Step by Step
Construct 2 Platformer: Step by StepShahed Chowdhuri
 
[LaravelConf Taiwan 2019] 忘掉 foreach,從此學會 Collection!
[LaravelConf Taiwan 2019] 忘掉 foreach,從此學會 Collection![LaravelConf Taiwan 2019] 忘掉 foreach,從此學會 Collection!
[LaravelConf Taiwan 2019] 忘掉 foreach,從此學會 Collection!LaravelConfTaiwan
 
cpbricks context diagram
cpbricks context diagramcpbricks context diagram
cpbricks context diagrami i
 

Was ist angesagt? (20)

Introduction to IPFS & Filecoin - longer version
Introduction to IPFS & Filecoin - longer versionIntroduction to IPFS & Filecoin - longer version
Introduction to IPFS & Filecoin - longer version
 
Pattern based problem solving-published
Pattern based problem solving-publishedPattern based problem solving-published
Pattern based problem solving-published
 
Qt for beginners part 1 overview and key concepts
Qt for beginners part 1   overview and key conceptsQt for beginners part 1   overview and key concepts
Qt for beginners part 1 overview and key concepts
 
[JCConf 2023] 從 Kotlin Multiplatform 到 Compose Multiplatform:在多平台間輕鬆共用業務邏輯與 U...
[JCConf 2023] 從 Kotlin Multiplatform 到 Compose Multiplatform:在多平台間輕鬆共用業務邏輯與 U...[JCConf 2023] 從 Kotlin Multiplatform 到 Compose Multiplatform:在多平台間輕鬆共用業務邏輯與 U...
[JCConf 2023] 從 Kotlin Multiplatform 到 Compose Multiplatform:在多平台間輕鬆共用業務邏輯與 U...
 
Python Modules, Packages and Libraries
Python Modules, Packages and LibrariesPython Modules, Packages and Libraries
Python Modules, Packages and Libraries
 
What is Kotlin Multiplaform? Why & How?
What is Kotlin Multiplaform? Why & How? What is Kotlin Multiplaform? Why & How?
What is Kotlin Multiplaform? Why & How?
 
Windows 10 Nt Heap Exploitation (Chinese version)
Windows 10 Nt Heap Exploitation (Chinese version)Windows 10 Nt Heap Exploitation (Chinese version)
Windows 10 Nt Heap Exploitation (Chinese version)
 
Hack & Fix, Hands on ColdFusion Security Training
Hack & Fix, Hands on ColdFusion Security TrainingHack & Fix, Hands on ColdFusion Security Training
Hack & Fix, Hands on ColdFusion Security Training
 
BAS004-1_伺服器硬體基礎_v181026
BAS004-1_伺服器硬體基礎_v181026BAS004-1_伺服器硬體基礎_v181026
BAS004-1_伺服器硬體基礎_v181026
 
Javaで簡単にgpgpu aparapi
Javaで簡単にgpgpu aparapiJavaで簡単にgpgpu aparapi
Javaで簡単にgpgpu aparapi
 
An Introduction to OpenSAF 5.17.2011
An Introduction to OpenSAF 5.17.2011An Introduction to OpenSAF 5.17.2011
An Introduction to OpenSAF 5.17.2011
 
Introduction to DirectX 11
Introduction to DirectX 11Introduction to DirectX 11
Introduction to DirectX 11
 
使用 Passkeys 打造無密碼驗證服務
使用 Passkeys 打造無密碼驗證服務使用 Passkeys 打造無密碼驗證服務
使用 Passkeys 打造無密碼驗證服務
 
.NET 7 升級教戰手冊_V1.0.pdf
.NET 7 升級教戰手冊_V1.0.pdf.NET 7 升級教戰手冊_V1.0.pdf
.NET 7 升級教戰手冊_V1.0.pdf
 
Pharo Networking by Example
Pharo Networking by ExamplePharo Networking by Example
Pharo Networking by Example
 
(2013 DEVIEW) 멀티쓰레드 프로그래밍이 왜이리 힘드나요?
(2013 DEVIEW) 멀티쓰레드 프로그래밍이  왜이리 힘드나요? (2013 DEVIEW) 멀티쓰레드 프로그래밍이  왜이리 힘드나요?
(2013 DEVIEW) 멀티쓰레드 프로그래밍이 왜이리 힘드나요?
 
Java Nio 2
Java Nio 2Java Nio 2
Java Nio 2
 
Construct 2 Platformer: Step by Step
Construct 2 Platformer: Step by StepConstruct 2 Platformer: Step by Step
Construct 2 Platformer: Step by Step
 
[LaravelConf Taiwan 2019] 忘掉 foreach,從此學會 Collection!
[LaravelConf Taiwan 2019] 忘掉 foreach,從此學會 Collection![LaravelConf Taiwan 2019] 忘掉 foreach,從此學會 Collection!
[LaravelConf Taiwan 2019] 忘掉 foreach,從此學會 Collection!
 
cpbricks context diagram
cpbricks context diagramcpbricks context diagram
cpbricks context diagram
 

Andere mochten auch

Realize Gaming - Video Poker Sell Book
Realize Gaming - Video Poker Sell BookRealize Gaming - Video Poker Sell Book
Realize Gaming - Video Poker Sell BookTimothy Nottke
 
Another Side of Poker | Anatolii Henis
Another Side of Poker | Anatolii HenisAnother Side of Poker | Anatolii Henis
Another Side of Poker | Anatolii HenisJessica Tams
 
The Strathclyde Poker Research Environment
The Strathclyde Poker Research EnvironmentThe Strathclyde Poker Research Environment
The Strathclyde Poker Research EnvironmentLuke Dicken
 
"Bwin - P5 a future proof Poker platform"
"Bwin - P5 a future proof Poker platform""Bwin - P5 a future proof Poker platform"
"Bwin - P5 a future proof Poker platform"gerold kathan
 
Planning poker in a nutshell
Planning poker in a nutshellPlanning poker in a nutshell
Planning poker in a nutshellSeb Rose
 
Tech Talk: Standup Poker: How One Hack Revolutionized Our Daily Standup
Tech Talk: Standup Poker: How One Hack Revolutionized Our Daily StandupTech Talk: Standup Poker: How One Hack Revolutionized Our Daily Standup
Tech Talk: Standup Poker: How One Hack Revolutionized Our Daily StandupCA Technologies
 
Poker in Numbers
Poker in NumbersPoker in Numbers
Poker in NumbersPokerCoUk
 
Beyond Planning Poker - Agile 2011
Beyond Planning Poker - Agile 2011Beyond Planning Poker - Agile 2011
Beyond Planning Poker - Agile 2011James Grenning
 
Use of cognitive and performance enhancing medications in poker players
Use of cognitive and performance enhancing medications in poker playersUse of cognitive and performance enhancing medications in poker players
Use of cognitive and performance enhancing medications in poker playersKevin Clauson
 
Poker Boom in the Video Game Industry | Pawel Weder
Poker Boom in the Video Game Industry | Pawel WederPoker Boom in the Video Game Industry | Pawel Weder
Poker Boom in the Video Game Industry | Pawel WederJessica Tams
 
Infiniti Poker Marketing Plan - MBA Marketing Class
Infiniti Poker Marketing Plan - MBA Marketing ClassInfiniti Poker Marketing Plan - MBA Marketing Class
Infiniti Poker Marketing Plan - MBA Marketing ClassSam Bishop
 
AI Strategies for Solving Poker Texas Hold'em
AI Strategies for Solving Poker Texas Hold'emAI Strategies for Solving Poker Texas Hold'em
AI Strategies for Solving Poker Texas Hold'emGiovanni Murru
 
The cost of irrationality - how poker players perform better by avoiding cogn...
The cost of irrationality - how poker players perform better by avoiding cogn...The cost of irrationality - how poker players perform better by avoiding cogn...
The cost of irrationality - how poker players perform better by avoiding cogn...Lasse Ringstad
 
Planning Poker estimating technique
Planning Poker estimating techniquePlanning Poker estimating technique
Planning Poker estimating techniqueSuhail Jamaldeen
 
Product Market Fit Poker
Product Market Fit PokerProduct Market Fit Poker
Product Market Fit PokerMatt Johnson
 
Ontology of Poker
Ontology of PokerOntology of Poker
Ontology of PokerBarry Smith
 

Andere mochten auch (20)

Ultimate Poker Tour - Press Kit
Ultimate Poker Tour - Press KitUltimate Poker Tour - Press Kit
Ultimate Poker Tour - Press Kit
 
Realize Gaming - Video Poker Sell Book
Realize Gaming - Video Poker Sell BookRealize Gaming - Video Poker Sell Book
Realize Gaming - Video Poker Sell Book
 
Another Side of Poker | Anatolii Henis
Another Side of Poker | Anatolii HenisAnother Side of Poker | Anatolii Henis
Another Side of Poker | Anatolii Henis
 
The Strathclyde Poker Research Environment
The Strathclyde Poker Research EnvironmentThe Strathclyde Poker Research Environment
The Strathclyde Poker Research Environment
 
"Bwin - P5 a future proof Poker platform"
"Bwin - P5 a future proof Poker platform""Bwin - P5 a future proof Poker platform"
"Bwin - P5 a future proof Poker platform"
 
Planning poker in a nutshell
Planning poker in a nutshellPlanning poker in a nutshell
Planning poker in a nutshell
 
Tech Talk: Standup Poker: How One Hack Revolutionized Our Daily Standup
Tech Talk: Standup Poker: How One Hack Revolutionized Our Daily StandupTech Talk: Standup Poker: How One Hack Revolutionized Our Daily Standup
Tech Talk: Standup Poker: How One Hack Revolutionized Our Daily Standup
 
Poker in Numbers
Poker in NumbersPoker in Numbers
Poker in Numbers
 
Beyond Planning Poker - Agile 2011
Beyond Planning Poker - Agile 2011Beyond Planning Poker - Agile 2011
Beyond Planning Poker - Agile 2011
 
Use of cognitive and performance enhancing medications in poker players
Use of cognitive and performance enhancing medications in poker playersUse of cognitive and performance enhancing medications in poker players
Use of cognitive and performance enhancing medications in poker players
 
Introduction Priority Poker (En)
Introduction Priority Poker (En)Introduction Priority Poker (En)
Introduction Priority Poker (En)
 
The Art Of War In Poker
The Art Of War In PokerThe Art Of War In Poker
The Art Of War In Poker
 
Poker Boom in the Video Game Industry | Pawel Weder
Poker Boom in the Video Game Industry | Pawel WederPoker Boom in the Video Game Industry | Pawel Weder
Poker Boom in the Video Game Industry | Pawel Weder
 
Infiniti Poker Marketing Plan - MBA Marketing Class
Infiniti Poker Marketing Plan - MBA Marketing ClassInfiniti Poker Marketing Plan - MBA Marketing Class
Infiniti Poker Marketing Plan - MBA Marketing Class
 
Basic Poker Strategy
Basic Poker StrategyBasic Poker Strategy
Basic Poker Strategy
 
AI Strategies for Solving Poker Texas Hold'em
AI Strategies for Solving Poker Texas Hold'emAI Strategies for Solving Poker Texas Hold'em
AI Strategies for Solving Poker Texas Hold'em
 
The cost of irrationality - how poker players perform better by avoiding cogn...
The cost of irrationality - how poker players perform better by avoiding cogn...The cost of irrationality - how poker players perform better by avoiding cogn...
The cost of irrationality - how poker players perform better by avoiding cogn...
 
Planning Poker estimating technique
Planning Poker estimating techniquePlanning Poker estimating technique
Planning Poker estimating technique
 
Product Market Fit Poker
Product Market Fit PokerProduct Market Fit Poker
Product Market Fit Poker
 
Ontology of Poker
Ontology of PokerOntology of Poker
Ontology of Poker
 

Ähnlich wie Live Poker Analysis Using Python

A CTF Hackers Toolbox
A CTF Hackers ToolboxA CTF Hackers Toolbox
A CTF Hackers ToolboxStefan
 
Capturing NIC and Kernel TX and RX Timestamps for Packets in Go
Capturing NIC and Kernel TX and RX Timestamps for Packets in GoCapturing NIC and Kernel TX and RX Timestamps for Packets in Go
Capturing NIC and Kernel TX and RX Timestamps for Packets in GoScyllaDB
 
Rootkit on Linux X86 v2.6
Rootkit on Linux X86 v2.6Rootkit on Linux X86 v2.6
Rootkit on Linux X86 v2.6fisher.w.y
 
Playing CTFs for Fun & Profit
Playing CTFs for Fun & ProfitPlaying CTFs for Fun & Profit
Playing CTFs for Fun & Profitimpdefined
 
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321ExperiencesSharingOnEmbeddedSystemDevelopment_20160321
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321Teddy Hsiung
 
Python utan-stodhjul-motorsag
Python utan-stodhjul-motorsagPython utan-stodhjul-motorsag
Python utan-stodhjul-motorsagniklal
 
Deep learning - the conf br 2018
Deep learning - the conf br 2018Deep learning - the conf br 2018
Deep learning - the conf br 2018Fabio Janiszevski
 
pa-pe-pi-po-pure Python Text Processing
pa-pe-pi-po-pure Python Text Processingpa-pe-pi-po-pure Python Text Processing
pa-pe-pi-po-pure Python Text ProcessingRodrigo Senra
 
Simplest-Ownage-Human-Observed… - Routers
 Simplest-Ownage-Human-Observed… - Routers Simplest-Ownage-Human-Observed… - Routers
Simplest-Ownage-Human-Observed… - RoutersLogicaltrust pl
 
Filip palian mateuszkocielski. simplest ownage human observed… routers
Filip palian mateuszkocielski. simplest ownage human observed… routersFilip palian mateuszkocielski. simplest ownage human observed… routers
Filip palian mateuszkocielski. simplest ownage human observed… routersYury Chemerkin
 
LSFMM 2019 BPF Observability
LSFMM 2019 BPF ObservabilityLSFMM 2019 BPF Observability
LSFMM 2019 BPF ObservabilityBrendan Gregg
 
CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak
CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak   CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak
CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak PROIDEA
 
Gpu workshop cluster universe: scripting cuda
Gpu workshop cluster universe: scripting cudaGpu workshop cluster universe: scripting cuda
Gpu workshop cluster universe: scripting cudaFerdinand Jamitzky
 
Assignment no39
Assignment no39Assignment no39
Assignment no39Jay Patel
 

Ähnlich wie Live Poker Analysis Using Python (20)

Debug generic process
Debug generic processDebug generic process
Debug generic process
 
A CTF Hackers Toolbox
A CTF Hackers ToolboxA CTF Hackers Toolbox
A CTF Hackers Toolbox
 
Capturing NIC and Kernel TX and RX Timestamps for Packets in Go
Capturing NIC and Kernel TX and RX Timestamps for Packets in GoCapturing NIC and Kernel TX and RX Timestamps for Packets in Go
Capturing NIC and Kernel TX and RX Timestamps for Packets in Go
 
Pycon Sec
Pycon SecPycon Sec
Pycon Sec
 
R-House (LSRC)
R-House (LSRC)R-House (LSRC)
R-House (LSRC)
 
Basic Linux kernel
Basic Linux kernelBasic Linux kernel
Basic Linux kernel
 
Rootkit on Linux X86 v2.6
Rootkit on Linux X86 v2.6Rootkit on Linux X86 v2.6
Rootkit on Linux X86 v2.6
 
Playing CTFs for Fun & Profit
Playing CTFs for Fun & ProfitPlaying CTFs for Fun & Profit
Playing CTFs for Fun & Profit
 
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321ExperiencesSharingOnEmbeddedSystemDevelopment_20160321
ExperiencesSharingOnEmbeddedSystemDevelopment_20160321
 
Python utan-stodhjul-motorsag
Python utan-stodhjul-motorsagPython utan-stodhjul-motorsag
Python utan-stodhjul-motorsag
 
C&cpu
C&cpuC&cpu
C&cpu
 
Deep learning - the conf br 2018
Deep learning - the conf br 2018Deep learning - the conf br 2018
Deep learning - the conf br 2018
 
pa-pe-pi-po-pure Python Text Processing
pa-pe-pi-po-pure Python Text Processingpa-pe-pi-po-pure Python Text Processing
pa-pe-pi-po-pure Python Text Processing
 
Simplest-Ownage-Human-Observed… - Routers
 Simplest-Ownage-Human-Observed… - Routers Simplest-Ownage-Human-Observed… - Routers
Simplest-Ownage-Human-Observed… - Routers
 
Filip palian mateuszkocielski. simplest ownage human observed… routers
Filip palian mateuszkocielski. simplest ownage human observed… routersFilip palian mateuszkocielski. simplest ownage human observed… routers
Filip palian mateuszkocielski. simplest ownage human observed… routers
 
LSFMM 2019 BPF Observability
LSFMM 2019 BPF ObservabilityLSFMM 2019 BPF Observability
LSFMM 2019 BPF Observability
 
Data Analysis in Python
Data Analysis in PythonData Analysis in Python
Data Analysis in Python
 
CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak
CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak   CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak
CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak
 
Gpu workshop cluster universe: scripting cuda
Gpu workshop cluster universe: scripting cudaGpu workshop cluster universe: scripting cuda
Gpu workshop cluster universe: scripting cuda
 
Assignment no39
Assignment no39Assignment no39
Assignment no39
 

Mehr von Roger Barnes

The life of a web request - techniques for measuring and improving Django app...
The life of a web request - techniques for measuring and improving Django app...The life of a web request - techniques for measuring and improving Django app...
The life of a web request - techniques for measuring and improving Django app...Roger Barnes
 
Building data flows with Celery and SQLAlchemy
Building data flows with Celery and SQLAlchemyBuilding data flows with Celery and SQLAlchemy
Building data flows with Celery and SQLAlchemyRoger Barnes
 
Introduction to SQL Alchemy - SyPy June 2013
Introduction to SQL Alchemy - SyPy June 2013Introduction to SQL Alchemy - SyPy June 2013
Introduction to SQL Alchemy - SyPy June 2013Roger Barnes
 
Towards Continuous Deployment with Django
Towards Continuous Deployment with DjangoTowards Continuous Deployment with Django
Towards Continuous Deployment with DjangoRoger Barnes
 
Scraping recalcitrant web sites with Python & Selenium
Scraping recalcitrant web sites with Python & SeleniumScraping recalcitrant web sites with Python & Selenium
Scraping recalcitrant web sites with Python & SeleniumRoger Barnes
 
Intro to Pinax: Kickstarting Your Django Apps
Intro to Pinax: Kickstarting Your Django AppsIntro to Pinax: Kickstarting Your Django Apps
Intro to Pinax: Kickstarting Your Django AppsRoger Barnes
 

Mehr von Roger Barnes (6)

The life of a web request - techniques for measuring and improving Django app...
The life of a web request - techniques for measuring and improving Django app...The life of a web request - techniques for measuring and improving Django app...
The life of a web request - techniques for measuring and improving Django app...
 
Building data flows with Celery and SQLAlchemy
Building data flows with Celery and SQLAlchemyBuilding data flows with Celery and SQLAlchemy
Building data flows with Celery and SQLAlchemy
 
Introduction to SQL Alchemy - SyPy June 2013
Introduction to SQL Alchemy - SyPy June 2013Introduction to SQL Alchemy - SyPy June 2013
Introduction to SQL Alchemy - SyPy June 2013
 
Towards Continuous Deployment with Django
Towards Continuous Deployment with DjangoTowards Continuous Deployment with Django
Towards Continuous Deployment with Django
 
Scraping recalcitrant web sites with Python & Selenium
Scraping recalcitrant web sites with Python & SeleniumScraping recalcitrant web sites with Python & Selenium
Scraping recalcitrant web sites with Python & Selenium
 
Intro to Pinax: Kickstarting Your Django Apps
Intro to Pinax: Kickstarting Your Django AppsIntro to Pinax: Kickstarting Your Django Apps
Intro to Pinax: Kickstarting Your Django Apps
 

Kürzlich hochgeladen

From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 

Kürzlich hochgeladen (20)

From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 

Live Poker Analysis Using Python

  • 1. The adventures of poker, packets, pipes and Python Roger Barnes
  • 2. I like playing online poker
  • 3. But I could be better at it
  • 4. I needed a poker buddy All in! That's a terrible hand!
  • 6. Packet capture options from your (rooted) Android device - wifi or 3G ● apps - eg Shark for Root ● tcpdump - via shell
  • 7. Packet capture options from your router or another device on the network (if promiscuous mode) - wifi only ● tcpdump/libpcap ● wireshark/tshark ● pcapy ● ngrep
  • 8. Hackable routers There are many devices and firmwares to choose from (see dd-wrt and tomato-usb) I have Netgear WNR3500L with Tomato-USB ● ssh built in ● Additional packages installed using Optware ○ http://tomatousb.org/doc:optware ○ Includes python, tshark, ngrep, wget, some build tools, ...
  • 9. Initial capture using tshark tshark -i eth1 -w capture.pcap -f "host 192.168.1.106 and (port 9400 or port 9500)"
  • 11. IPython Notebook http://ipython.org/ipython-doc/dev/interactive/htmlnotebook.html
  • 12. Parsing game state More IPython notebook work to figure out sequence of events, card values, player actions etc
  • 13. Mapping card values def cardmapper(val): vals = '23456789TJQKA' suits = 'cdhs' result = divmod(val, 13) return vals[result[1]] + suits[result[0]] print cardmapper(44) # 7s print cardmapper(21) # Td print cardmapper(17) # 6d print cardmapper(51) # As print cardmapper(7) # 9c print cardmapper(0) # 2c
  • 14. Getting live capture data ● tshark? Too hard ● pcapy? Maybe ● ngrep? Probably
  • 15. Getting live capture data into Python ● Install pcapy on router? Too hard ● zmq on router? Too hard ● SSH and pipe? Maybe
  • 16. Running hand analysis ● Run directly on router? Too hard
  • 17. Solution - ssh, ngrep and pipes ssh $router "ngrep ..." | python -u poker-buddy.py
  • 18. Pipes Piping data into Python is easy You can read stdin... import sys while True: l = sys.stdin.readline(): Alternatively use the Unix-like fileinput module... import fileinput for line in fileinput.input(): ... fileinput reads from a list of files, or else stdin
  • 19. Pipes Watch out for buffering! python -u
  • 20. Now for some poker smarts Loads of resources on the web ● Poker games generally ○ starting hand rankings ○ odds calculations etc
  • 21. Now for some poker smarts Easy lookup tables in python... # Unprocessed space separated string dump stats_rankings = """AA 2.3200 550,632 KK 1.6700 551,878 ... lots more lines 32s -0.1600 369,182""" # Now convert to structured data stats_rankings = dict([ (line.split()[0], (rank + 1, float(line.split()[1]))) for rank, line in enumerate(stats_rankings.split("n")) ])
  • 22. Now for some poker smarts Python specific ● pypoker-eval ○ Wrapper for poker-eval toolkit ○ Run hand simulations ● machine learning systems ○ endless possibilities ● Lots of other resources at: http://pokerai.org/pf3/viewforum.php?f=32
  • 23. Code def read_raw_from_stdin(): line = '' while 1: l = sys.stdin.readline() line += l.strip() if '''we have a complete line''': parse_update(line) line = '' if __name__ == "__main__": read_raw_from_stdin()
  • 24. Code def parse_update(update_str): player_cards = get_cards(update_str) if player_cards: my_cards = [v for v in player_cards if v[0] != '__'] if my_cards: rank_starting_hand(my_cards[0]) else: player_cards = old_player_cards # global state excluded community_cards = get_cards(update_str, player=False) if community_cards: print("Community cards %s" % community_cards) rank_hand(player_cards, community_cards)
  • 25. Code e = PokerEval() def rank_hand(pocket_cards, community_cards, iterations=100000): unknown_cards = ['__'] * (5 - len(community_cards)) result = e.poker_eval(game = "holdem", pockets = pocket_cards, iterations = iterations, board = community_cards + unknown_cards) for i, data in enumerate(result['eval']): print(pocket_cards[i], "%2d%%" % (float(data['ev']) / 10), data['winhi'], data['losehi'], data['tiehi'])
  • 26. Game in progress - poker-buddy.py Player cards [['__', '__'], ['__', '__'], ['Ac', 'Kc'], ['__', '__'], ['__', '__']] Group 1 (5, 0.77)
  • 27. Game in progress - poker-buddy.py Community cards ['Th', '5s', '9h'] ['__', '__'] 21% 20486 77811 1703 ['__', '__'] 21% 20267 78013 1720 ['Ac', 'Kc'] 15% 14880 84332 788 ['__', '__'] 21% 20386 77819 1795 ['__', '__'] 21% 20207 78074 1719
  • 28. Game in progress - poker-buddy.py Community cards ['Th', '5s', '9h', 'Jc', '6s'] ['__', '__'] 24% 24185 74694 1121 ['__', '__'] 24% 24332 74502 1166 ['Ac', 'Kc'] 1% 1019 98870 111 ['__', '__'] 24% 24005 74893 1102 ['__', '__'] 24% 24148 74698 1154
  • 29. Summary ● Python can be used for packet capture ○ pycapy ● Python for data processing ○ Pipes, unbuffered input (-u option), stdin, fileinput module ● Python on embedded devices ○ Optware on routers & other embedded devices ● IPython Notebook great for analysis... ...and documenting what you found ● There's a library for almost everything ○ eg pypoker-eval
  • 30. Thanks! Questions? Code (warts and all): https://github.com/mindsocket/poker-buddy